Greasemonkey脚本在特定注释之间删除HTML? [英] Greasemonkey script to remove HTML between specific comments?
问题描述
为了阻止我在加载页面时不想执行的JavaScript,我希望有一个Greasemonkey脚本来删除两个HTML注释标记之间的所有内容。例如:
In order to block some JavaScript that I don't want to execute when I load a page, I would like to have a Greasemonkey script that deletes everything between two HTML comment tags. For example:
<!-- sub script -->
Lines containing script elements to be removed
<!-- end sub script -->
我之前尝试使用建议给我的示例脚本删除脚本元素,但它不是按预期工作。那个脚本是这样的:
I have previously tried removing the script elements using a sample script that was suggested to me, but it isn't working as expected. That script was this:
var script = document.querySelectorAll('script[src*="example.com"]');
for (var i = 0, len = script.length; i < len; i++) {
script[i].parentNode.removeChild(scriptscript[i]);
}
简单地说,它不会删除脚本元素,因为我希望它将。我知道评论元素在页面之间是一致的,如果我可以使用它们作为标记来开始和结束搜索并简单地删除它们之间的所有内容,我相信它可以解决问题。
Simply put, it doesn't remove the script elements as I had hoped it would. I know that the comment elements are consistent between pages and if I could use those as the markers to begin and end a search and simply delete everything in between, I believe it would solve the problem.
任何指导都将不胜感激。说我是JavaScript的新手是轻描淡写,但我是一个快速学习者。
Any guidance would be appreciated. To say I'm new to JavaScript would be an understatement, but I'm a quick learner.
推荐答案
你不能只需删除包含它的< script>
即可删除JavaScript脚本。
You can't remove a JavaScript script by just removing the <script>
which included it.
这是因为一旦浏览器解析了< script>
,脚本运行,并且没有办法撤销它。
That's because once browser parses the <script>
, the script runs, and there's no way to undo that.
但在某些浏览器上你可以使用 beforescriptexecute
事件:
But on some browsers you can block the script just before it runs, using beforescriptexecute
event:
window.addEventListener('beforescriptexecute', function(e) {
if (~e.target.src.indexOf('example.com')) {
e.preventDefault();
}
}, true);
注意你的GM脚本必须在要阻止的脚本之前运行,以确保使用
Note your GM script must run before the script you want to block, to be sure, use
@run-at document-start
这篇关于Greasemonkey脚本在特定注释之间删除HTML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!