Skip to content

Instantly share code, notes, and snippets.

Created March 6, 2023 11:38
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Injected script to use Promise-based async calls with WebKit user script message handlers
// SPDX-License-Identifier: MIT
(function (_console, _window, _Map, _Promise) {
"use strict";
let currentTxnId = 0;
const txnMap = new _Map();
const warning = _console.warn;
function makeTxnId() {
while (txnMap.has(currentTxnId))
return currentTxnId++;
function finishAsyncApiCall(txnId, how, value) {
let entry = txnMap.get(txnId);
if (entry === undefined) {
warning("attempted to " + how + " unknown promise " + txnId);
return false;
} else {
return true;
function asyncApiCall(name, args) {
const message = {
txnId: makeTxnId(),
args: args,
return new _Promise((resolve, reject) => {
// Store the resolve/reject callbacks indexed by the transaction identifier;
// so later the UIProcess can call window.__finishAsyncApiCall() passing the
// identifier back, which allows finding back which functions to call and
// settle the promise.
txnMap.set(message.txnId, {
resolve: resolve,
reject: reject,
message: message,
_window.__finishAsyncApiCall = finishAsyncApiCall;
_window.asyncApiCall = asyncApiCall;
})(console, window, Map, Promise);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment