2010-07-15 82 views
4

嵌入式JS一个页面的HTML如下:的Greasemonkey:停止运行

<script type="text/javascript"> 
    // some code 
</script> 

我的Greasemonkey脚本需要防止脚本运行。我怎样才能做到这一点?


更新:据我所知,在一般情况下,这是不可能的。但是,在我的具体情况下,我可能有漏洞?

<script type="text/javascript"> 
    if (!window.devicePixelRatio) { 
    // some code that I -don't- want to be run, regardless of the browser 
    } 
</script> 

在嵌入式脚本运行之前有什么方法可以定义window.devicePixelRatio吗?

回答

2

用户脚本在页面加载后运行,所以你不能。

除非,代码使用“onload”事件。

用户脚本执行 DOM满载后,但在此之前的onload 发生。这意味着您的脚本 可以立即开始,不需要 等待onload。

+0

谢谢。我想我会尽我所能去尝试并撤消脚本的功能。我已经用一些可能的方式更新了这个问题......或者说,当我的GM脚本运行时,它已经太晚了? – Mala 2010-07-15 05:16:12

+0

不与用户脚本。嵌入式JavaScript在浏览器加载后立即运行。用户脚本在整个页面加载后运行。 – 2010-07-15 05:41:36

1

另一种选择是使用Privoxy而不是GreaseMonkey。您只需使用Privoxy作为您的代理(在本地主机上)并搜索/替换您不喜欢的字符串。

+0

这是一个非常麻烦的选择。 – beppe9000 2017-10-02 17:56:33

12

现在可以使用@run-at document-start和HTML5的beforescriptexecute。仅在FF24中进行测试。

// ==UserScript== 
... 
// @run-at   document-start 
// ==/UserScript== 

//a search string to uniquely identify the script 
//for example, an anti-adblock script 
var re = /adblock/i; 

window.addEventListener('beforescriptexecute', function(e) { 

    if(re.test(e.target.text)){ 

     e.stopPropagation(); 
     e.preventDefault(); 
    } 

}, true); 
+0

+1,但请注意,这仅适用于FF,并且自FF版本4以来一直受支持。此外,在此情况下使用'.textContent'代替'.text'可能更好。 – 2013-09-29 02:06:50

1

回复:

是否有某种方式嵌入的脚本运行之前,我可以定义window.devicePixelRatio

现在有。像这样:

// ==UserScript== 
// @name  _Pre set devicePixelRatio 
// @include http://YOUR_SERVER.COM/YOUR_PATH/* 
// @run-at document-start 
// @grant none 
// ==/UserScript== 
//-- @grant none is imporatant in this case. 

window.devicePixelRatio = "Unimportant string or function or whatever"; 


在一般情况下:

由于火狐4版,这是目前可能仅Firefox浏览器。使用the checkForBadJavascripts utility来调整beforescriptexecute的功率。像这样:

// ==UserScript== 
// @name  _Block select inline JS 
// @include http://YOUR_SERVER.COM/YOUR_PATH/* 
// @require https://gist.github.com/raw/2620135/checkForBadJavascripts.js 
// @run-at document-start 
// @grant GM_addStyle 
// ==/UserScript== 
/*- The @grant directive is needed to work around a design change 
    introduced in GM 1.0. It restores the sandbox. 
*/ 

checkForBadJavascripts ([ 
    [false, /window\.devicePixelRatio/, null] 
]); 


此块第一内嵌脚本,包含window.devicePixelRatio完全。如果要选择修改该脚本的某些部分,请参阅this answer和/或this answer