Skip to content

Instantly share code, notes, and snippets.

@aperezdc
Created March 6, 2023 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aperezdc/a112c6a61a5a11885eac2498702e3a6d to your computer and use it in GitHub Desktop.
Save aperezdc/a112c6a61a5a11885eac2498702e3a6d to your computer and use it in GitHub Desktop.
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))
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 {
entry[how](value);
txnMap.delete(txnId);
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.webkit.messageHandlers[name].postMessage(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