Since inline module scripts don't have document.currentScript, we can't simply append document.currentScript.remove() at the end of the script.
document.currentScript.remove() would be fine, but e.g. wrapping the script in a function/block scope, or something like that would materially affect the code (e.g. variable scoping), so I can't do stuff like that.You could try assigning a class or id to the user script and use it to remove the script.
let uniqueClass = "_userlandscript" + Math.random().toString().replace(".", "");
let code = `console.log("hello folks and world");`;
// Append self-deletion snippet:
code += `
document.querySelector('.${uniqueClass}').remove();
console.log("Exists:", document.querySelector('.${uniqueClass}'));`;
let script = document.createElement('script');
script.textContent = code;
script.type = "module";
script.classList.add(uniqueClass);
document.body.append(script);
As noted by @Bergi, you may want to consider prepending the document.querySelector('.${uniqueClass}').remove() code to the script, so it is guaranteed to run even if there is an error within the userland code (except in thec case of a SyntaxError).
I am not at all sure how useful it would be for script modules in general - AFAIK trying to import data from an inline script fails with CORS errors because script modules require retrieval from a network to work as documented.
Warning: this is a hack in response to a request for a hack, provided "as is" under the "don't sue me license" for your consideration.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With