Last active
May 26, 2022 17:18
-
-
Save mecab/52773e9c7222e1c7b2b4eb0ea809f156 to your computer and use it in GitHub Desktop.
executeScript polyfill PoC that supports both of Chrome and Firefox (manifest v3 and v2)
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
type AnyFunc = (...args: any[]) => any; | |
function wrapFuncToCode<T extends () => any>(func: T): string; | |
function wrapFuncToCode<T extends AnyFunc>(func: T, args: Parameters<T>): string; | |
function wrapFuncToCode<T extends AnyFunc>(func: T, args: any[] = []): string | |
{ | |
return `(${func.toString()}).apply(this, ${JSON.stringify(args)})`; | |
} | |
async function executeScript<T extends () => any>(tabId: number, injection: { func: T }): Promise<ReturnType<T>>; | |
async function executeScript<T extends AnyFunc>(tabId: number, injection: { func: T, args: Parameters<T> }): Promise<ReturnType<T>>; | |
async function executeScript(tabId: number, injection: { file: string }): Promise<any>; | |
async function executeScript<T extends AnyFunc>(tabId: number, { func, args, file }: { func?: T, args?: any, file?: string }): Promise<ReturnType<T> | any> { | |
let result: any; | |
if (process.env['VENDOR'] === 'firefox') { | |
( | |
[ result ] = await browser.tabs.executeScript(tabId, { | |
... func ? { code : wrapFuncToCode(func, args) } : {}, | |
... file ? { file } : {}, | |
}) | |
); | |
} else { | |
( | |
[ { result } = { result: undefined } ] = await browser.scripting.executeScript({ | |
target: { tabId }, | |
... func ? { func, args } : {}, | |
... file ? { files: [ file ] } : {}, | |
}) | |
); | |
} | |
return result as ReturnType<T>; | |
} | |
// assume we had tabId | |
(async() => { | |
await executeScript(tabId, { | |
func: () => { return 42; }, | |
}); | |
await executeScript(tabId, { | |
func: (a, b) => { return a + b; }, | |
args: [1, 2], | |
}); | |
await executeScript(tabId, { | |
file: '/script/contentscript.js', | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment