gpt4 book ai didi

Javascript:通过获取 native 函数来防止函数被覆盖

转载 作者:行者123 更新时间:2023-11-29 15:57:35 26 4
gpt4 key购买 nike

是否可以通过返回标准函数来防止重新定义 javascript 函数。

让我解释一下:

我有一个模块可以检测操纵 DOM 的浏览器扩展。

但是,任何 native 函数都可以通过该扩展重新定义。

因此,我试图通过 iframe 元素恢复 native 功能。

在下面的代码中,我这样做了,但是我得到了对 observe 方法的非法调用。

( function() { 

//protection against overriding of MutationObserver and XMLHttpRequest method
var iframe_tag = document.createElement('iframe');
document.body.appendChild(iframe_tag);
window.MutationObserver = iframe_tag.contentWindow.MutationObserver;
window.XMLHttpRequest = iframe_tag.contentWindow.XMLHttpRequest;

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
//Here we detected a change....
};

// binding to window object --> does not work Illegal invocation
MutationObserver.prototype.observe = MutationObserver.prototype.observe.bind(this);

// Create an observer instance linked to the callback function
var bodyobserver = new MutationObserver(callback);

// Start observing the target node for configured mutations
bodyobserver .observe(document.body, config);


} ) ();

这是这样做的方法吗/我做错了什么?

最佳答案

你应该覆盖整个原型(prototype)

window.objectToOverride.prototype = Object.create(iframe.objectToOverride.prototype)

结果:

( function() { 

//protection against overriding of MutationObserver and XMLHttpRequest method
var iframe_tag = document.createElement('iframe');
document.body.appendChild(iframe_tag);
window.MutationObserver.prototype = Object.create(iframe_tag.contentWindow.MutationObserver.prototype);
window.XMLHttpRequest.prototype = Object.create(iframe_tag.contentWindow.XMLHttpRequest.prototype);

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
//Here we detected a change....
};

// binding to window object --> does not work Illegal invocation
// Not needed anymore
//MutationObserver.prototype.observe = MutationObserver.prototype.observe.bind(this);

// Create an observer instance linked to the callback function
var bodyobserver = new MutationObserver(callback);

// Start observing the target node for configured mutations
bodyobserver.observe(document.body, {});


} ) ();

关于Javascript:通过获取 native 函数来防止函数被覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57285937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com