let gettingActiveTab = browser.tabs.query({
active: true,
currentWindow: true,
});
gettingActiveTab.then(updateTab);Work with the Bookmarks API / notebook
Work with the Bookmarks API
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
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.`);
}
}
}function isSupportedProtocol(urlString) {
let supportedProtocols = ["https:", "http:", "file:"];
let url = document.createElement("a");
url.href = urlString;
return supportedProtocols.includes(url.protocol);
}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,
});
}browser.browserAction.onClicked.addListener(toggleBookmark);function toggleBookmark() {
if (currentBookmark) {
browser.bookmarks.remove(currentBookmark.id);
} else {
browser.bookmarks.create({ title: currentTab.title, url: currentTab.url });
}
}// 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);