remove appended script javascript
I did some more tests, and before you'll get a correct answer to your question (hope there is a one) you can try this:
<button onclick="foo()">ShowHTML</button>
<script>
(function foo(){
var b=function moo(){
var c=document.getElementsByTagName('script');
alert(document.body.innerHTML);
c[0].parentElement.removeChild(c[0]);
alert(document.body.innerHTML);
}
var a=setTimeout(b,1000);
b=null;
})();
foo=null;
</script>
This is just a test code, but it contains an idea, how you possible could solve the problem. It removes <sript>
from the DOM, and the last line destroys all functionality of the script.
(The code also has a little detail, which shows, that setTimeout
will do eval()
, no matter how it is argumented...?)
I would simply check to see if you've already added the script. Adding it and then removing is adds unnecessary complexity. Something like this should work:
var scriptAdded = false;
if(scriptAdded == false) {
document.body.appendChild(script);
scriptAdded = true;
}
just add an id to the script element when you create it.
this way you don't have to iterate over all 'script' tags that match your source. instead, just do
const script = document.createElement("script");
script.src = "SOME_SCRIPT";
script.id = 'SOME_ID';
document.body.append(script);
and then to remove
const scriptElem = document.getElementById('SOME_ID');
scriptElem.remove()
some dude explains here why its ok to add id to script tags https://stackoverflow.com/a/2741488/13156886
Basically you can remove script tag by using a function similar to this one:
function removeJS(filename){
var tags = document.getElementsByTagName('script');
for (var i = tags.length; i >= 0; i--){ //search backwards within nodelist for matching elements to remove
if (tags[i] && tags[i].getAttribute('src') != null && tags[i].getAttribute('src').indexOf(filename) != -1)
tags[i].parentNode.removeChild(tags[i]); //remove element by calling parentNode.removeChild()
}
}
Note, it use filename parameter to identify target script to remove. Also please note that target script could be already executed at the time you're trying to remove it.