我试图为Tampermonkey编写一个脚本来阻止执行特定的内联脚本标记。页面正文看起来像这样
<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>
我尝试使用我的Tampermonkey脚本删除script
标记,但如果我run it at document-start
或document-body
script
标记尚不存在。如果我在document-end
或document-idle
处运行script
标记我想删除,请在执行Tampermonkey脚本之前运行。
如何阻止执行script
代码?
注意:我要阻止执行的实际script
标记包含window.location = 'redirect-url'
。因此,在这种情况下防止重新加载也足够了。
版本:
答案 0 :(得分:1)
删除document-start
上的脚本标记(由wOxxOm建议):
(function() {
'use strict';
window.stop();
const xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href);
xhr.onload = () => {
var html = xhr.responseText
.replace(/<script\b[\s\S]*?<\/script>/g, s => {
// check if script tag should be replaced/deleted
if (s.includes('window.location')) {
return '';
} else {
return s;
}
});
document.open();
document.write(html);
document.close();
};
xhr.send();
})();
答案 1 :(得分:1)
没有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 });
})();