1.0.10 • Published 10 years ago
chrome-promise-temp v1.0.10
chrome-promise
DEPRECATED
I'll no longer to maintain this project, please have a look to chrome-call.
Chrome API using promises.
Installation
Use npm
npm install chrome-promiseOr bower
bower install chrome-promiseOr 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)); // => {"foo":"bar"}
});Options
The constructor accepts two parameters: chrome and Promise.
chromeis the chrome API object. By default (or when null or undefined are used), it is the 'chrome' global property.Promiseis 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();
// try...catch
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);
}
});
// promise.catch
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.