chrome-promise
Chrome API using promises.
Note: I'm no longer adding features to this library (only bug fixing). You can check other alternative libraries at the end of this file.
Installation
Use npm
npm install chrome-promise
Or yarn
yarn add chrome-promise
Or download chrome-promise.js file.
You can include it in your HTML like this:
Or you can use ES2015 import statement:
;
Compatibility
It supports Chrome 34 or higher, but it should work in older versions. Create an issue if it doesn't work for your version.
Examples
Use local storage.
chromepstoragelocal;
Detect languages of all tabs.
chromeptabs;
Options
If you are testing with node, you can provide a mock for the chrome API (sinon-chrome is a good choice) using the constructor.
const ChromePromise = ;const chrome = ; const chromep = chrome ;
The constructor accepts an options parameter with the following properties:
-
chrome
: the chrome API object. By default (or when null or undefined are used), it is the 'chrome' global property. -
Promise
: the object used to create promises. By default, it is the 'Promise' global property.
Notes
This library is not a replacement of the chrome
api.
It should be used only for functions that have a callback.
// this returns a rejected promise (because a callback is added to getManifest)chromepruntime; // this workschromeruntime;
When there's a callback with multiple parameters, the promise will return an array with the callback arguments.
chromephid; // Using babel or chrome >= 49chromephid;
Only APIs that are enabled in the manifest will be available in the ChromePromise
instance.
If the API is undefined, first check the permissions
in the manifest.json
of your project.
// manifest.json "permissions": "tabs" // main.jsconsole // "object"console // "undefined"
Synchronous-looking code
If you are using babel or chrome ≥ 55, you can use async/await to achieve this.
{ await chromepstoragelocal; ; const items = await chromepstoragelocal; ;}; // try...catch { try const tabs = await chromeptabs; const promises = tabs; const languages = await Promiseallpromises; ; catcherr ; };
If you are not using babel and you need to support chrome ≥ 39, it can be done with generator functions. Using the methods Q.async and Q.spawn from the Q library, the previous examples can be rewritten as:
Q; // try...catchQ; // promise.catchQ;
You can also use the co library instead of Q.