A lightweight polyfill library for Promise-based WebExtension APIs in Chrome
Go to file
Luca Greco 61d92ea79b feat: Added devtools.inspectedWindow.eval and devtools.panels.create to wrapped APIs.
To be able to wrap the devtools API namespaces, this patch applies the
following changes:

- fix: Prevent Proxy violation exception on the read-only/non-configurable devtools property
  by using an empty object with the `chrome` API object as its prototype
  as the root Proxy target (the Proxy instances returned for the
  `chrome` API object) and add a related test case.

- fix: Added support for a new `singleCallbackArg` metadata property,
  which prevents devtools.panels.create to resolve an array of
  parameters (See the related Chromium issue at
  https://bugs.chromium.org/p/chromium/issues/detail?id=768159)
  and add the related test cases.

- test: Changes to the test case related to proxy getter/setter behavior
  on non wrapped properties:

  in the "deletes proxy getter/setter that are not wrapped" test case from
  the "test-proxied-properties.js" test file, we ensure that when a
  getter/setter is called for a "non-wrapped" property, the getter/setter
  is going to affect the original target object, unfortunately this in
  not true anymore for the root object (the `chrome` API object) because
  we are using an empty object (which has the `chrome` API object as its
  prototype and it is not exposed outside of the polyfill sources)
  as the target of the Proxy instance related to it,
  this change to the target of the Proxy has been needed to prevent the
  TypeError exception raised by the Proxy instance when we try to access
  the "devtools" property (which is non-configurable and read-only on the
  `chrome` API object).
2017-09-25 22:20:07 +02:00
src feat: Added devtools.inspectedWindow.eval and devtools.panels.create to wrapped APIs. 2017-09-25 22:20:07 +02:00
test feat: Added devtools.inspectedWindow.eval and devtools.panels.create to wrapped APIs. 2017-09-25 22:20:07 +02:00
.eslintrc fix: Limit eslint to the project's own rules (#46) 2017-08-20 13:33:56 +02:00
.gitignore test: introduced a test suite for unit testing. 2016-11-07 16:33:42 +01:00
.travis.yml chore: Publish tagged releases to npm from travis job 2017-04-13 14:48:04 +02:00
Gruntfile.js fix: Lock gruntify-eslint version to fix build errors (#42) 2017-08-20 13:26:43 +02:00
LICENSE Initial commit 2016-10-06 12:02:51 -07:00
README.md docs: Added build status badge to the README.md (#45) 2017-08-20 13:35:53 +02:00
api-metadata.json feat: Added devtools.inspectedWindow.eval and devtools.panels.create to wrapped APIs. 2017-09-25 22:20:07 +02:00
package.json chore: bump version for release 0.1.2 2017-09-25 20:42:56 +02:00

README.md

WebExtension browser API Polyfill Build Status

This library allows extensions written for the Promise-based WebExtension/BrowserExt API being standardized by the W3 Browser Extensions group to be used without modification in Google Chrome.

Building

To build, assuming you're already installed node >= 6 and npm, simply run:

npm install
npm run build
npm run test

This will install all the npm dependencies and build both non-minified and minified versions of the final library, and output them to dist/browser-polyfill.js and dist/browser-polyfill.min.js, respectively, and finally executes the unit tests on the generated dist files.

Basic Setup

In order to use the polyfill, it must be loaded into any context where browser APIs are accessed. The most common cases are background and content scripts, which can be specified in manifest.json:

{
  // ...

  "background": {
    "scripts": [
      "browser-polyfill.js",
      "background.js"
    ]
  },

  "content_scripts": [{
    // ...
    "js": [
      "browser-polyfill.js",
      "content.js"
    ]
  }]
}

For HTML documents, such as browserAction popups, or tab pages, it must be included more explicitly:

<!DOCTYPE html>
<html>
  <head>
    <script type="application/javascript" src="browser-polyfill.js"></script>
    <script type="application/javascript" src="popup.js"></script>
  </head>
  <!-- ... -->
</html>

And for dynamically-injected content scripts loaded by tabs.executeScript, it must be injected by a separate executeScript call, unless it has already been loaded via a content_scripts declaration in manifest.json:

browser.tabs.executeScript({file: "browser-polyfill.js"});
browser.tabs.executeScript({file: "content.js"}).then(result => {
  // ...
});

Using the Promise-based APIs

The Promise-based APIs in the browser namespace work, for the most part, very similarly to the callback-based APIs in Chrome's chrome namespace. The major differences are:

  • Rather than receiving a callback argument, every async function returns a Promise object, which resolves or rejects when the operation completes.

  • Rather than checking the chrome.runtime.lastError property from every callback, code which needs to explicitly deal with errors registers a separate Promise rejection handler.

  • Rather than receiving a sendResponse callback to send a response, onMessage listeners simply return a Promise whose resolution value is used as a reply.

  • Rather than nesting callbacks when a sequence of operations depend on each other, Promise chaining is generally used instead.

  • For users of an ES7 transpiler, such as Babel, the resulting Promises are generally used with async and await, rather than dealt with directly.

Examples

The following code will retrieve a list of URLs patterns from the storage API, retrieve a list of tabs which match any of them, reload each of those tabs, and notify the user that is has been done:

browser.storage.get("urls").then(({urls}) => {
  return browser.tabs.query({url: urls});
}).then(tabs => {
  return Promise.all(
    Array.from(tabs, tab => browser.tabs.reload(tab.id)));
  );
}).then(() => {
  return browser.notifications.create({
    type: "basic",
    iconUrl: "icon.png",
    title: "Tabs reloaded",
    message: "Your tabs have been reloaded",
  });
}).catch(error => {
  console.error(`An error occurred while reloading tabs: ${error.message}`);
});

Or, using an async function:

async function reloadTabs() {
  try {
    let {urls} = await browser.storage.get("urls");

    let tabs = await browser.tabs.query({url: urls});

    await Promise.all(
      Array.from(tabs, tab => browser.tabs.reload(tab.id)));
    );

    await browser.notifications.create({
      type: "basic",
      iconUrl: "icon.png",
      title: "Tabs reloaded",
      message: "Your tabs have been reloaded",
    });
  } catch (error) {
    console.error(`An error occurred while reloading tabs: ${error.message}`);
  }
}

It's also possible to use Promises effectively using two-way messaging. Communication between a background page and a tab content script, for example, looks something like this from the background page side:

browser.tabs.sendMessage("get-ids").then(results => {
  processResults(results);
});

And like this from the content script:

browser.runtime.onMessage.addListener(msg => {
  if (msg == "get-ids") {
    return browser.storage.get("idPattern").then(({idPattern}) => {
      return Array.from(document.querySelectorAll(idPattern),
                        elem => elem.textContent);
    });
  }
});

or:

browser.runtime.onMessage.addListener(async function(msg) {
  if (msg == "get-ids") {
    let {idPattern} = await browser.storage.get("idPattern");

    return Array.from(document.querySelectorAll(idPattern),
                      elem => elem.textContent);
  }
});

Or vice versa.