ChromeExtensionAsync
Promise wrapper for the Chrome extension API so that it can be used with async/await rather than callbacks
Install / Use
/learn @KeithHenry/ChromeExtensionAsyncREADME
Chrome Extension Async
Promise wrapper for the Chrome extension API so that it can be used with async/await rather than callbacks
The Extension API provided by Chrome uses callbacks.
However, Chrome now supports async and await keywords.
This library wraps Chrome extension API callback methods in promises, so that they can be called with async and await.
Once activated against the Chrome API each callback function gets a Promise version.
Chrome supports ES2017 syntax, so in extensions we can take full advantage of it.
Installation
Use bower
bower install chrome-extension-async
Or npm
npm i chrome-extension-async
Or download chrome-extension-async.js file and include it directly:
<script type="text/javascript" src="chrome-extension-async.js"></script>
TypeScript definitions for the altered API are in chrome-extension-async.d.ts
You must reference chrome-extension-async.js before your code attempts to use the features of this, as it needs to run across the Chrome API before you call it. <script async> is not currently supported, but you can use <script defer> so long as the scripts that use this are also defer and after it.
Examples
Using the basic Chrome API, let's:
- Get the current active tab
- Execute a script in that tab
- Do something with the first result of the script
function startDoSomething(script, callback) {
// Fire off the tabs query and continue in the callback
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
// Check API for any errors thrown
if (chrome.runtime.lastError) {
// Handle errors from chrome.tabs.query
}
else {
var activeTab = tabs[0];
// Fire off the injected script and continue in the callback
chrome.tabs.executeScript(activeTab.id, { code: script }, function(results) {
// Check API for any errors thrown, again
if (chrome.runtime.lastError) {
// Handle errors from chrome.tabs.executeScript
}
else {
var firstScriptResult = results[0];
callback(firstScriptResult);
}
});
}
});
}
This works, but the nested callbacks are painful to debug and maintain, and they can quickly lead to 'callback hell'.
Instead, with this library, we can use await:
async function doSomething(script) {
try {
// Query the tabs and continue once we have the result
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const activeTab = tabs[0];
// Execute the injected script and continue once we have the result
const results = await chrome.tabs.executeScript(activeTab.id, { code: script });
const firstScriptResult = results[0];
return firstScriptResult;
}
catch(err) {
// Handle errors from chrome.tabs.query, chrome.tabs.executeScript or my code
}
}
// If you want to use the same callback you can use Promise syntax too:
doSomething(script).then(callback);
Some callbacks take multiple parameters - in these cases the Promise will be a combined object:
async function checkUpdate() {
try {
// API is chrome.runtime.requestUpdateCheck(function (status, details) { ... });
// Instead we use deconstruction-assignment and await
const { status, details } = await chrome.runtime.requestUpdateCheck();
alert(`Status: ${status}\nDetails: ${JSON.stringify(details)}`);
}
catch(err) {
// Handle errors from chrome.runtime.requestUpdateCheck or my code
}
}
This also includes a check against chrome.runtime.lastError, so that you can use try-catch to get exceptions thrown from the Chrome API.
Event Listener API
These are not included.
For instance chrome.browserAction.onClicked.addListener takes a callback function, but executes it every time the event fires.
It is not suitable for a Promise or async call.
Execute Injected Scripts Asynchronously With chrome.tabs.executeAsyncFunction
New in v3.2 is chrome.tabs.executeAsyncFunction, an enhancement to the tabs API that allows a popup or browser/page action to easily execute asynchronous code in a page. This:
- Adds
chrome.runtime.sendMessageto the injected script to return the result. - Uses
chrome.runtime.onMessage.addListenerto listen for the injected event. - Fires the script with
chrome.tabs.executeScript. - Wraps the whole thing in a promise that resolves with the final result.
- Adds all the relevant error handling by rejecting the promise.
const scriptToExecute = async function() {
// await promises in the tab
}
try {
// The await returns the complete result of the function
const results = await chrome.tabs.executeAsyncFunction(
activeTab.id, // If null this will be the current tab
scriptToExecute, // Will be .toString and applied to the {code:} property
123, 'foo'); // Additional parameters will be passed to scriptToExecute
// results now holds the output of the asynchronous code run in the page
}
catch(err) {
// Any error either setting up or executing the script
// Note that errors from the page will be re-thrown copies
}
chrome.tabs.executeAsyncFunction can take a function, string, or executeScript details with the code property set. The script must be async or return a Promise. Details with a file property are not supported. Scripts that output multiple values are not supported.
Unlike chrome.tabs.executeScript this can take a function, but note that it just converts the function to a string to pass it. This means that it must be self contained (it cannot call other user defined functions) and it cannot be native (as many serialise to function foobar() { [native code] }).
This is held in its own file: execute-async-function.js:
<script type="text/javascript" src="execute-async-function.js"></script>
This relies on a chrome.runtime.onMessage.addListener subscription, so it will fail if called from within a listener event.
Create and Reload Tabs with chrome.tabs.createAndWait and chrome.tabs.reloadAndWait
New in v3.4 is chrome.tabs.createAndWait and chrome.tabs.reloadAndWait. The normal chrome.tabs.create and chrome.tabs.reload functions execute their callbacks as soon as the tab is created, before the tab has finished loading. This makes it difficult to create or reload a tab, and then execute a content script on the page. chrome.tabs.createAndWait and chrome.tabs.reloadAndWait are an enhancement to the tabs API that waits until the tab has finished loading the url, and is ready to execute scripts. They pair great with chrome.tabs.executeAsyncFunction.
They:
- Call
chrome.tabs.createorchrome.tabs.reload, await the results, and grab the tab's id. - Use
chrome.tabs.onUpdated.addListenerto listen for the 'completed' status for the tab's id. - Wrap the whole thing in a promise that resolves with the final result.
- Use
chrome.tabs.onRemoved.addListenerandchrome.tabs.onReplaced.addListenerto detect if the tab is removed or replaced before the loading finishes, and rejects the promise with an Error. - Use an auto-timeout feature. If the page doesn't load in the specified milliseconds, or one of the three listeners is never called, the promise will be rejected with an Error. The value of the timeout is configurable with an optional parameter. The default value is 12e4 milliseconds (2 minutes).
chrome.tabs.createAndWait takes in the same parameters as chrome.tabs.create except for the callback, and returns an object containing the same properties as the parameters passed to the callback for the chrome.tabs.onUpdated event.
try {
// Create a new tab and wait for it to finish loading. The url will take 5 seconds to finish loading.
// Try closing the tab before it finishes loading, and you will see the error.
const {tabId, changeInfo, tab} = await chrome.tabs.createAndWait({ url: "http://www.mocky.io/v2/5d59a32e3000006c2ed84c7a?mocky-delay=5000ms", active:true });
// Now that it is finished loading, it is ready to execute content scripts.
const scriptResults = await chrome.tabs.executeAsyncFunction(tab.id, () => { alert('The tab finished loading.');} );
// Voila! In two lines you've created a new tab, and executed a content script on it!
}
catch (err) {
alert(err);
}
chrome.tabs.reloadAndWait takes in the same parameters as chrome.tabs.reload except for the callback, and returns an object containing the same properties as the parameters passed to the callback for the chrome.tabs.onUpdated event.
try {
// Get the
