The WebExtension JavaScript APIs can be used inside the add-on's background scripts and in any browser action or page action popups that the add-on defines. A few of these APIs can also be accessed by an add-on's content scripts (see the list in the content script guide).
To use the more powerful APIs you need to request permission in your add-on's manifest.json.
You can access the APIs using either the chrome namespace or the browser namespace:
function logTabs(tabs) {
console.log(tabs);
}
chrome.tabs.query({currentWindow: true}, logTabs);
function logTabs(tabs) {
console.log(tabs);
}
browser.tabs.query({currentWindow: true}, logTabs);
These are equivalent, except:
- the
browsernamespace isn't available in Google Chrome, so if you want to run the same code on Chrome, usechrome - if you use the
browsernamespace, you can use promises instead of callbacks for asynchronous functions. SeeCallbacks and promisesbelow.
See the complete list of JavaScript APIs.
Callbacks and promises
Many of the APIs are asynchronous, returning a value via a callback.
If these functions need to communicate an error, they do so by setting extension.lastError. If a function can set lastError, then you need to check it in your callback.
For example, cookies.set() will set lastError if the add-on does not have permission to set the cookie:
function logCookie(c) {
if (browser.extension.lastError) {
console.error(browser.extension.lastError);
} else {
console.log(c);
}
}
browser.cookies.set(
{url: "https://developer.mozilla.org/"},
logCookie
);
If you use the browser namespace and omit the callback, then these functions will return a Promise. The first argument to Promise.then() will be given the callback's arguments, and the second argument to Promise.then() will be given lastError:
function logCookie(c) {
console.log(c);
}
function logError(e) {
console.error(e);
}
var setCookie = browser.cookies.set(
{url: "https://developer.mozilla.org/"}
);
setCookie.then(logCookie, logError);