Chrome API using promises.
Use npm
npm install chrome-promise
Or bower
bower install chrome-promise
Or download chrome-promise.js file.
You can include it in your HTML like this:
<script type="text/javascript" src="chrome-promise.js"></script>
It needs Chrome 46 or higher. If you need to support an older version, please create an issue.
Use local storage.
const chromep = new ChromePromise();
chromep.storage.local.set({foo: 'bar'}).then(function() {
alert('foo set');
return chromep.storage.local.get('foo');
}).then(function(items) {
alert(JSON.stringify(items)); // => {"foo":"bar"}
});
Detect languages of all tabs.
const chromep = new ChromePromise();
chromep.tabs.query({}).then((tabs) => {
let promises = tabs.map(tab => chromep.tabs.detectLanguage(tab.id));
return Promise.all(promises);
}).then((languages) => {
alert('Languages: ' + languages.join(', '));
}).catch((err) => {
alert(err.message);
});
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.
It can be achieved with generator functions. Using the methods Q.async and Q.spawn from the Q library, the previous examples can be rewritten as:
const chromep = new ChromePromise();
Q.spawn(function* () {
yield chromep.storage.local.set({foo: 'bar'});
alert('foo set');
let items = yield chromep.storage.local.get('foo');
alert(JSON.stringify(items));
});
// try...catch
Q.spawn(function* () {
try {
let tabs = yield chromep.tabs.query({});
let promises = tabs.map(tab => chromep.tabs.detectLanguage(tab.id));
let languages = yield Promise.all(promises);
alert('Languages: ' + languages.join(', '));
} catch(err) {
alert(err);
}
});
// promise.catch
Q.async(function* () {
let tabs = yield chromep.tabs.query({});
let languages = yield Promise.all(tabs.map((tab) => (
chromep.tabs.detectLanguage(tab.id);
)));
alert('Languages: ' + languages.join(', '));
})().catch(function(err) {
alert(err);
});
You can also use the co library or async/await instead of Q.