且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Chrome 扩展程序停止执行函数

更新时间:2023-12-05 20:53:34

我在开发 不要跟踪我 Google 用户脚本/扩展.

I faced the same problem during development of the Don't track me Google User script / extension.

#重要提示Chrome 内容脚本中的 window 对象无法以任何方式直接访问.
我测试了很多方法,唯一可靠的方法是通过动态创建的脚本标记注入代码.看看这个答案,或我的扩展程序的源代码 了解更多信息.

#Important note The window object in a Chrome contentscript cannot be accessed directly, in any way.
I have tested many methods, and the only reliable method is injecting the code through a dynamically created script tag. Have a look at this answer, or my extension's source code for more information.

我使用 Object.defineProperty.使用此方法,您可以定义一个属性,并指定有关 getter、setter 和属性描述符的信息.在你的情况下:

I solved it by using Object.defineProperty. With this method, you can define a property, and specify information about the getter, setter and property descriptors. In your case:

Object.defineProperty(window, 'foo', {
    value: function(){/*This function cannot be overridden*/}
});

或者,如果您想捕获该变量,并在以后使用它:

Or, if you want to capture the variable, and use it later:

(function() {
    var originalFoo = function(){/*Default*/};
    Object.defineProperty(window, 'foo', {
        get: function(){
            if (confirm('function logic')) return function(){/*dummy*/};
            else return originalFoo;
        },
        set: function(fn){originalFoo = fn;}
    });
})();


##Bug 在 Chrome 17 [Bug #115452](http://code.google.com/p/chromium/issues/detail?id=115452) [已修复!](http://code.google.com/p/chromium/issues/detail?id=115452#hc4)在 Chrome 17 中,使用 V8 3.7.12.12(但不是在 Chrome 16 中,使用 V8 3.6.6.19),**函数声明覆盖属性描述符**.
见 http://jsfiddle.net/bHUag/
请注意,当函数声明和属性描述符方法位于同一块中时,此错误 *似乎* 不适用.不过,这是错误的.效果是不可见的,因为函数声明总是在代码块之前进行评估.因此,首先评估 `function foo(){}`,然后是其余的代码.


##Bug in Chrome 17 [Bug #115452](http://code.google.com/p/chromium/issues/detail?id=115452) [Fixed!](http://code.google.com/p/chromium/issues/detail?id=115452#hc4) In Chrome 17, using V8 3.7.12.12 (but not in Chrome 16, using V8 3.6.6.19), **Function declarations override the property descriptors**.
See http://jsfiddle.net/bHUag/
Note that this bug *seems* to not be applied when the function declaration and property descriptor method are in the same block. This is false, though. The effect is not visible, because function declarations are always evaluated before the code block. So, `function foo(){}` is evaluated first, then the rest of the code.
<script>
Object.defineProperty(window, 'foo', {value: function(){return 5;} });
</script><script>
function foo(){return 1};
alert(foo()); // Shows 5 in all browsers except for Chrome v17
</script>