chrome-promise
DEPRECATED
I'll no longer to maintain this project, please have a look to chrome-call.
![build status](https://img.shields.io/travis/tfoxy/chrome-promise.svg)
Chrome API using promises.
Installation
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>
Examples
Detect languages of all tabs.
chrome.promise = new ChromePromise();
chrome.promise.tabs.query({}).then(function(tabs) {
var promises = tabs.map(function(tab) {
return chrome.promise.tabs.detectLanguage(tab.id);
});
return Promise.all(promises);
}).then(function(languages) {
alert('Languages: ' + languages.join(', '));
}).catch(function(err) {
alert(err.message);
});
Use local storage.
chrome.promise = new ChromePromise();
chrome.promise.storage.local.set({foo: 'bar'}).then(function() {
alert('foo set');
return chrome.promise.storage.local.get('foo');
}).then(function(items) {
alert(JSON.stringify(items));
});
Options
The constructor accepts two parameters: chrome and Promise.
-
chrome
is the chrome API object. By default (or when null or undefined are used), it is the 'chrome' global property.
-
Promise
is the object used to create promises. By default, it is the 'Promise' global property.
Synchronous-looking code
Starting from Chrome 39, you can use
generator functions.
Using the methods Q.async
and Q.spawn
from the Q library, the previous examples can be rewritten as:
chrome.promise = new ChromePromise();
Q.spawn(function* () {
try {
var tabs = yield chrome.promise.tabs.query({});
var languages = yield Promise.all(tabs.map(function(tab) {
return chrome.promise.tabs.detectLanguage(tab.id);
}));
alert('Languages: ' + languages.join(', '));
} catch(err) {
alert(err);
}
});
Q.async(function* () {
var tabs = yield chrome.promise.tabs.query({});
var languages = yield Promise.all(tabs.map(function(tab) {
return chrome.promise.tabs.detectLanguage(tab.id);
}));
alert('Languages: ' + languages.join(', '));
})().catch(function(err) {
alert(err);
});
Q.spawn(function* () {
yield chrome.promise.storage.local.set({foo: 'bar'});
alert('foo set');
var items = yield chrome.promise.storage.local.get('foo');
alert(JSON.stringify(items));
});
You can also use the co library instead of Q.