DEV Community

Hank Chiu
Hank Chiu

Posted on • Edited on

3 3

A simple technique to promisify Chrome extension API

Update:
Now you can use toPromise from crx-esm!


One of my pain when developing a Chrome extension is looking at the callback-based APIs. There are some polyfill promisified all the APIs. (e.g. webextension-polyfill)

If you just want some light-weight solution, here you are.

The simple trick is to take advantage of the truth that the callback function is always the last argument, and you can create a simple helper function to promisify the chrome API:

function toPromise(api) {
  return (...args) => {
    return new Promise((resolve) => {
      api(...args, resolve);
    });
  };
}
Enter fullscreen mode Exit fullscreen mode

and use it like:

toPromise(chrome.tabs.query)({}).then(...);
Enter fullscreen mode Exit fullscreen mode

This just works for me most of the time.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (4)

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

I would like to have a crossbrowser solution how would this look in Firefox?

Collapse
 
hankchiutw profile image
Hank Chiu

Do you mean for Firefox extension?

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

The Extension API yes, simple develop once run in every browser.

Thread Thread
 
hankchiutw profile image
Hank Chiu

From MDN, it says "Firefox also implements these APIs under the chrome namespace using callbacks".

So, I guess the code toPromise(chrome.tabs.query)({}).then(...); should work on Firefox as well.(hopefully)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay