问题
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.
Any guidance would be appreciated. To say I'm new to JavaScript would be an understatement, but I'm a quick learner.
回答1:
You can't remove a JavaScript script by just removing the <script>
which included it.
That's because once browser parses the <script>
, the script runs, and there's no way to undo that.
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);
Note your GM script must run before the script you want to block, to be sure, use
@run-at document-start
来源:https://stackoverflow.com/questions/23413400/greasemonkey-script-to-remove-html-between-specific-comments