I'm trying to write a script for Tampermonkey that prevents the execution of a specific inline script tag. The body of the page looks something like this
<body>
<!-- the following script tag should be executed-->
<script type="text/javascript">
alert("I'm executed as normal")
</script>
<!-- the following script tag should NOT be executed-->
<script type="text/javascript">
alert("I should not be executed")
</script>
<!-- the following script tag should be executed-->
<script type="text/javascript">
alert("I'm executed as normal, too")
</script>
</body>
I tried to remove the script
tag using my Tampermonkey script, but if I run it at document-start
or document-body
the script
tag does not exist yet. If I run it at document-end
or document-idle
the script
tag I'd like to remove is run before my Tampermonkey script is executed.
How can I prevent execution of the script
tag?
Note: The actual script
tag that I'd like to prevent from executing contains window.location = 'redirect-url'
. So it would also be sufficient to prevent the reload in this case.
Versions:
Alternative version free of doc.write/XHR --
(() => {
'use strict';
let needle = '/window.location/';
if ( needle === '' || needle === '{{1}}' ) {
needle = '.?';
} else if ( needle.slice(0,1) === '/' && needle.slice(-1) === '/' ) {
needle = needle.slice(1,-1);
} else {
needle = needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
needle = new RegExp(needle);
const jsnode = () => {
try {
const jss = document.querySelectorAll('script');
for (const js of jss) {
if (js.outerHTML.match(needle)) {
js.remove();
}
}
} catch { }
};
const observer = new MutationObserver(jsnode);
observer.observe(document.documentElement, { childList: true, subtree: true });
})();