Code Monkey home page Code Monkey logo

chrome-promise's Introduction

chrome-promise

npm version bower version build status

Chrome API using promises.

Installation

Use npm

npm install chrome-promise

Or yarn

yarn add chrome-promise

Or bower

bower install chrome-promise

Or download chrome-promise.js file.

You can include it in your HTML like this:

<script src="chrome-promise.js"></script>

Or you can use ES2015 import statement:

import ChromePromise from 'chrome-promise';

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.

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);
});

Options

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.

const chromep = new ChromePromise();

// this returns a rejected promise (because a callback is added to getManifest)
chromep.runtime.getManifest();

// this works
chrome.runtime.getManifest();

When there's a callback with multiple parameters, the promise will return an array with the callback arguments.

const chromep = new ChromePromise();

chromep.hid.receive(4).then(function(args) {
  const reportId = args[0];
  const data = args[1];
  console.log(reportId, data);
});

// Using babel or chrome >= 49
chromep.hid.receive(4).then(([reportId, data]) => {
  console.log(reportId, data);
});

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.js
const chromep = new ChromePromise();
console.log(typeof chromep.tabs)  // "object"
console.log(typeof chromep.bookmarks)  // "undefined"

Synchronous-looking code

If you are using babel or chrome ≥ 55, you can use async/await to achieve this.

const chromep = new ChromePromise();

async function main() {
  await chromep.storage.local.set({foo: 'bar'});
  alert('foo set');
  const items = await chromep.storage.local.get('foo');
  alert(JSON.stringify(items));
}
main();

// try...catch
async function main2() {
  try {
    const tabs = await chromep.tabs.query({});
    const promises = tabs.map(tab => chromep.tabs.detectLanguage(tab.id));
    const languages = await Promise.all(promises);
    alert('Languages: ' + languages.join(', '));
  } catch(err) {
    alert(err);
  }
}
main2();

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:

const chromep = new ChromePromise();

Q.spawn(function* () {
  yield chromep.storage.local.set({foo: 'bar'});
  alert('foo set');
  const items = yield chromep.storage.local.get('foo');
  alert(JSON.stringify(items));
});

// try...catch
Q.spawn(function* () {
  try {
    const tabs = yield chromep.tabs.query({});
    const promises = tabs.map(tab => chromep.tabs.detectLanguage(tab.id));
    const languages = yield Promise.all(promises);
    alert('Languages: ' + languages.join(', '));
  } catch(err) {
    alert(err);
  }
});

// promise.catch
Q.async(function* () {
  const tabs = yield chromep.tabs.query({});
  const 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 instead of Q.

chrome-promise's People

Contributors

errorx666 avatar foray1010 avatar lmk123 avatar rafis avatar riggs avatar tfoxy avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.