I have a page hosted on a server which injects small portion of script to my index.html page and would like to remove this script before it runs.
Simplified example looks like this
<!doctype html>
<html lang="en">
<body>
<script id="removeme">
console.log("go");
</script>
</body>
</html>
I want to prevent the ‘console.log("go");’ from being executed.
I have tried to add a script which removes the removeme
script:
<!doctype html>
<html lang="en">
<body>
nothing to show
<script id="script_which_removes_the_other_script">
// First attempt
console.log("1 trying to remove " );
const unwantedScript = document.getElementById('removeme');
console.log("1 the script tag to remove: " + unwantedScript );
if (unwantedScript) {
unwantedScript.remove();
console.log('1 Unwanted script removed.');
}
else{
console.log('1 Did not found the script to remove.');
}
// Second attempt
document.addEventListener('DOMContentLoaded', () => {
console.log("2 trying to remove " );
const unwantedScript = document.getElementById('removeme');
console.log("2 the script tag to remove: " + unwantedScript );
if (unwantedScript) {
unwantedScript.remove();
console.log('2 Unwanted script removed.');
}
});
</script>
<script id="removeme">
console.log("go");
</script>
</body>
</html>
But neither block 1, neither block 2 cannot stop the method from being run.
The console output is as follows:
1 trying to remove
1 the script tag to remove: null
1 Did not found the script to remove.
go
2 trying to remove
2 the script tag to remove: [object HTMLScriptElement]
2 Unwanted script removed.
How can I prevent the function from the removeme
block from being run?
2
Answers
Try a more aggressive approach by removing the script element immediately as soon as it is created in the DOM.
Here is my approach, hope help you. Add the following code to the first script tag:
If the
<script>
tag is injected server-side by searching for the closing</body>
tag, then you could just not output it. Both the<html>
tag and the<body>
tag have optional end tags.Another options is to have the browser block the script:
Browsers include CSP. A Content Security Policy tells the browser what types of content it should execute. You can disable all inline
<script>
tags and only allow your own<script>
elements, either by linking them (<script src="">
) or by including anonce
attribute:This particular CSP value will allow
<script>
tags that come from the same server (/file.js
), from https links (https://example.com/file.js
) or if they include anonce
property with the valueabc123
. Note that the single quotes matter.If the script you’re trying to block is not inline but includes a src (
<script src="">
) then you remove either'self'
orhttps:
from the policy (whichever is applicable) and add thenonce
attribute to all of your own scripts.