Created
March 6, 2023 11:38
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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