Files
webextensions-examples/bookmark-it/background.js
wbamberg dead97bc38 Rewrite of bookmark-it, fixing issue 182 and some other problems (#186)
* Rewrite of bookmark-it, fixing issue 182 and some other problems

* Catch rejected promises

* Update with review comments, and some more fixes

* Revise fix to be much closer to original

* Remove extra semicolon
2017-05-09 14:23:19 -07:00

82 lines
2.1 KiB
JavaScript

var currentTab;
var currentBookmark;
/*
* Updates the browserAction icon to reflect whether the current page
* is already bookmarked.
*/
function updateIcon() {
browser.browserAction.setIcon({
path: currentBookmark ? {
19: "icons/star-filled-19.png",
38: "icons/star-filled-38.png"
} : {
19: "icons/star-empty-19.png",
38: "icons/star-empty-38.png"
},
tabId: currentTab.id
});
}
/*
* Add or remove the bookmark on the current page.
*/
function toggleBookmark() {
if (currentBookmark) {
browser.bookmarks.remove(currentBookmark.id);
} else {
browser.bookmarks.create({title: currentTab.title, url: currentTab.url});
}
}
browser.browserAction.onClicked.addListener(toggleBookmark);
/*
* Switches currentTab and currentBookmark to reflect the currently active tab
*/
function updateActiveTab(tabs) {
function isSupportedProtocol(urlString) {
var supportedProtocols = ["https:", "http:", "ftp:", "file:"];
var url = document.createElement('a');
url.href = urlString;
return supportedProtocols.indexOf(url.protocol) != -1;
}
function updateTab(tabs) {
if (tabs[0]) {
currentTab = tabs[0];
if (isSupportedProtocol(currentTab.url)) {
var searching = browser.bookmarks.search({url: currentTab.url});
searching.then((bookmarks) => {
currentBookmark = bookmarks[0];
updateIcon();
});
} else {
console.log(`Bookmark it! does not support the '${currentTab.url}' URL.`)
}
}
}
var gettingActiveTab = browser.tabs.query({active: true, currentWindow: true});
gettingActiveTab.then(updateTab);
}
// listen for bookmarks being created
browser.bookmarks.onCreated.addListener(updateActiveTab);
// listen for bookmarks being removed
browser.bookmarks.onRemoved.addListener(updateActiveTab);
// listen to tab URL changes
browser.tabs.onUpdated.addListener(updateActiveTab);
// listen to tab switching
browser.tabs.onActivated.addListener(updateActiveTab);
// listen for window switching
browser.windows.onFocusChanged.addListener(updateActiveTab);
// update when the extension loads initially
updateActiveTab();