A simple technique to promisify Chrome extension API
Hank Chiu
Posted on July 18, 2020
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);
});
};
}
and use it like:
toPromise(chrome.tabs.query)({}).then(...);
This just works for me most of the time.
💖 💪 🙅 🚩
Hank Chiu
Posted on July 18, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.