Please note, this is a STATIC archive of website developer.mozilla.org from November 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Using the JavaScript APIs

我们的志愿者还没有将这篇文章翻译为 中文 (简体)加入我们帮助完成翻译!

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 browser namespace isn't available in Google Chrome, so if you want to run the same code on Chrome, use chrome
  • if you use the browser namespace, you can use promises instead of callbacks for asynchronous functions. See Callbacks and promises below.

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);

文档标签和贡献者

 此页面的贡献者: wbamberg, andymckay
 最后编辑者: wbamberg,