更新时间: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;}
});
})();
<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>