mai*_*mic 7 html javascript tampermonkey
我正在尝试为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>
Run Code Online (Sandbox Code Playgroud)
我试图script使用Tampermonkey脚本删除该标签,但是如果我在上运行它 document-start或document-body该script标签尚不存在。如果我在运行它,document-end或者要删除document-idle的script标签在执行Tampermonkey脚本之前运行。
如何防止执行script标签?
注意:script我要阻止执行的实际标签包含window.location = 'redirect-url'。因此,在这种情况下,防止重新加载也就足够了。
版本:
删除脚本标签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();
})();
Run Code Online (Sandbox Code Playgroud)
小智 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 });
})();
Run Code Online (Sandbox Code Playgroud)