Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing inline module script *immediately* after execution?

Since inline module scripts don't have document.currentScript, we can't simply append document.currentScript.remove() at the end of the script.

Extra Notes/Context:

  • I'm talking about the synchronous phase of the module script's execution. I.e. once the script has synchronously executed, it should immediately be deleted, without e.g. waiting for an event loop tick in which other code might run.
  • I'm adding the module script to the DOM programmatically, and I don't control the code inside the script tag (i.e. it's "userland" code), or whether or not it's a module script, and so on. I can only do simple modifications to the script that don't affect the code - e.g. appending 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.
  • This is an unusual requirement, I must admit, but it's an unusual use case - related to dev tooling / live debugging / etc.
like image 755
joe Avatar asked Apr 29 '26 01:04

joe


1 Answers

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.

like image 139
traktor Avatar answered May 01 '26 15:05

traktor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!