This topic has been discussed a lot but here is my problem.
I receive from my api an object containing a script
[
{
"script": "<script src=xxx.js></script>",
"onScriptHead": true,
"onScriptOnLoad": false,
},
{
"script": "<script type="application/javascript">do something else</script>",
"onScriptHead": true,
"onScriptOnLoad": false,
}
]
Now my aim is to inject those script based on onScriptHead / onScriptLoad value.
I managed to create a code that can push a script on the head but only if there are no args inside the script tag
here is the code mentionned above
export const createScript = (scriptToInject: string, scriptSettings?: scriptSettingsProps) => {
const { onScriptHead } = scriptSettings ?? {};
const regexHTMLTag = /<([a-z]+)>/gi;
const inverseScriptRegex = /<[^>]*script/gi;
const addScriptTagToDom = (
retrieveScriptData: RegExpExecArray | string | null,
scriptTag?: any
) => {
const newScript = scriptTag
? document.createElement(`${scriptTag}`)
: document.createElement('script');
if (Array.isArray(retrieveScriptData)) {
const [, scriptData] = retrieveScriptData;
newScript.innerHTML = scriptData;
} else if (typeof retrieveScriptData === 'string') {
newScript.innerHTML = retrieveScriptData;
}
document.head.append(newScript);
};
let match = regexHTMLTag.exec(scriptToInject);
while (match !== null) {
const scriptTag = match[1];
const scriptRegex = new RegExp(`<${scriptTag}[^>]*>([\s\S]*?)</${scriptTag}>`);
const finalScript = scriptRegex.exec(scriptToInject) ? scriptRegex.exec(scriptToInject) : '';
if (onScriptHead) {
addScriptTagToDom(finalScript, scriptTag);
}
match = regexHTMLTag.exec(scriptToInject);
}
};
I cannot find a way to get the script, strip it down, then remount it using js document.xxx to use it in my dom
I have tried multiple regex and online solutions, but cannot find a dynamic way to inject my script after getting it from my api