Hi all,
I'm trying to use chrome.scripting.executeScript api with a variety of functions that have similar or the same code. I want to avoid having all this duplicate code, so I attempted to dynamically construct function steps by passing stringified functions as `args`. A greatly simplified sample below:
```
async function runSomeFunctions(tabId) {
const func = async (getElStr, anotherFuncStr) => {
// Transform the function string into an actual function
const getElementFromStr = new Function('return ' + getElStr)();
const anotherFuncFromStr = new Function('return ' + anotherFuncStr)();
const el = getElementFromStr('div > imput');
anotherFuncFromStr(el.value);
return el.value;
};
const result = await chrome.scripting.executeScript({
target: { tabId },
world: chrome.scripting['ExecutionWorld'].MAIN,
func,
args: [getElement.toString(), anotherFunc.toString()],
});
return result;
}
```
This generally works, but some sites were causing an error "This document requires 'TrustedHTML' assignment." or "This document requires 'TrustedScript' assignment." I found a workaround in a thread that does work, by adding:
``` if (window.trustedTypes && window.trustedTypes.createPolicy && !window.trustedTypes.defaultPolicy) {
window.trustedTypes.createPolicy('default', {
createHTML: string => string,
// Optional, only needed for script (url) tags
createScriptURL: string => string,
createScript: string => string,
});
}
```
I'm concerned about this approach since I haven't found a way to remove the policy after I create it and the function is done - not to mention that it might get flagged/denied on submission to CWS.
I know I can invoke some the functions through messaging to the content script, but I need it to happen in the service worker.
My questions are:
- Would this cause a rejection in CWS?
- If not, are there other risks?
- Is there another performant method to dynamically compose functions?