mirror of
https://github.com/mdn/webextensions-examples.git
synced 2026-04-16 14:28:33 +02:00
* Replace var with let in examples store-collected-images/webextension-plain/deps/uuidv4.js * Reverted third–party code
87 lines
2.3 KiB
JavaScript
87 lines
2.3 KiB
JavaScript
let currentTab;
|
|
let 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
|
|
});
|
|
browser.browserAction.setTitle({
|
|
// Screen readers can see the title
|
|
title: currentBookmark ? 'Unbookmark it!' : 'Bookmark it!',
|
|
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) {
|
|
let supportedProtocols = ["https:", "http:", "ftp:", "file:"];
|
|
let 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)) {
|
|
let 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.`)
|
|
}
|
|
}
|
|
}
|
|
|
|
let 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();
|