我有这样的页面结构:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
//here sought-for script should go
</script>
</head>
<body>
<script>
//Here the example of the script, that should not be executed, goes
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://test.com/img.jpg", false );
xmlHttp.send( null );
</script>
</body>
</html>
问题是 - 如何阻止<body>
部分中的脚本从<head>
部分的脚本中执行。
我为什么需要它?我需要阻止某些广告在没有的情况下使用任何浏览器扩展程序(例如Adblock)加载。简单广告隐藏使用CSS 赢得了 。
任何建议的解决方案都可行。任何挖掘方向都将受到赞赏。
重要更新:我只能访问<head>
部分。 xmlHttp的东西只是作为例子编写的。我需要阻止<body>
部分中的单个脚本执行,无论其内容是什么
答案 0 :(得分:1)
您可以在头上覆盖XMLHttpRequest定义,并在执行不需要的代码后回滚覆盖。
这样的事情应该有效
<!DOCTYPE html>
<html lang="en">
<head>
<script>
var originalXMLHttpRequest = XMLHttpRequest;
XMLHttpRequest = function(){
this.open = function( a,b,c ){
//do nothing
};
this.send =function(a){
//reset definition
XMLHttpRequest = originalXMLHttpRequest ;
};
}
</script>
</head>
<body>
<script>
//This script should not be executed
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://test.com/img.jpg", false );
xmlHttp.send( null );
</script>
</body>
</html>
第一个ajax将被忽略,在此之后将恢复正常的XMLHttpRequest,您可以更改此逻辑以满足您的需求
答案 1 :(得分:0)
你做不到。脚本在遇到时执行。周期。
但你的问题有些令人困惑。您对页面有足够的控制权来将自己的脚本注入head
元素,但无法控制body
中的内容?
您要禁用所有正文脚本,还是仅禁用该脚本?如果它就是那个,那很容易---
<script>
xmlHttpRequest = function () { };
</script>
对open
和send
的调用会出错,但是谁会关心。