在 Javascript 中覆盖默认浏览器对象
Getting overwritten default browser object in Javascript
有没有办法在全局范围内获取对象的默认值?
例如,假设我需要使用 Math.round
,但 Math.round
已被其他值覆盖。这是我正在谈论的示例:
// script1.js (can't be edited)
Math.round = () => null;
Object.freeze(Math); // delete Math.round method and freeze Math object
// script2.js (loads after script1.js)
console.log(Math.round(3.141592)); // should return 3
浏览器设置的默认值(function round() { [native code] }
)在Javascript被覆盖后是否可以获取?
我能想到的唯一解决方案是使用 iframe。每个 iframe 都会有它自己新创建的 window 对象,然后您可以在父框架中使用它(如果它们具有相同的来源)。
Math.round = () => null
const frame = document.createElement('iframe')
document.body.appendChild(frame)
Math.round(2.5) // null
frame.contentWindow.Math.round(2.5) // 3
如果您向函数提供正确的“this”,您甚至可以从 iframe 对当前页面调用 DOM 函数:
// will return your page's body, not the body in the iframe.
// This is because we're telling it to use our document object as "this", instead of the iframe's document.
frame.contentWindow.document.querySelector.call(document, 'body')
将来,我们可能会更好地支持 运行 脚本在他们自己的隔离“领域”中,在那里他们可以有自己独立的全球环境来处理。请参阅 this 即将发布的 ecmascript 提案以了解更多信息。 (在撰写本文时,目前处于第 2 阶段)
最后,我会指出几个替代解决方案,根据情况可能是更好的方法:
- 如果您可以完全控制该页面,那么您应该能够在加载这些讨厌的脚本之前保存全局变量。或者,您可以在 iframe 中加载脚本以隔离它的不良行为。
- 如果可能的话,最好只修改全局变量。脚本真的不应该触及它们,如果是,那可能是因为它们试图用 pollyfill 一些缺失的特性。脚本实际上对全局函数进行重大更改的情况很少见 - 但如果确实如此,向脚本作者提交错误报告以修复此行为可能是值得的。
有没有办法在全局范围内获取对象的默认值?
例如,假设我需要使用 Math.round
,但 Math.round
已被其他值覆盖。这是我正在谈论的示例:
// script1.js (can't be edited)
Math.round = () => null;
Object.freeze(Math); // delete Math.round method and freeze Math object
// script2.js (loads after script1.js)
console.log(Math.round(3.141592)); // should return 3
浏览器设置的默认值(function round() { [native code] }
)在Javascript被覆盖后是否可以获取?
我能想到的唯一解决方案是使用 iframe。每个 iframe 都会有它自己新创建的 window 对象,然后您可以在父框架中使用它(如果它们具有相同的来源)。
Math.round = () => null
const frame = document.createElement('iframe')
document.body.appendChild(frame)
Math.round(2.5) // null
frame.contentWindow.Math.round(2.5) // 3
如果您向函数提供正确的“this”,您甚至可以从 iframe 对当前页面调用 DOM 函数:
// will return your page's body, not the body in the iframe.
// This is because we're telling it to use our document object as "this", instead of the iframe's document.
frame.contentWindow.document.querySelector.call(document, 'body')
将来,我们可能会更好地支持 运行 脚本在他们自己的隔离“领域”中,在那里他们可以有自己独立的全球环境来处理。请参阅 this 即将发布的 ecmascript 提案以了解更多信息。 (在撰写本文时,目前处于第 2 阶段)
最后,我会指出几个替代解决方案,根据情况可能是更好的方法:
- 如果您可以完全控制该页面,那么您应该能够在加载这些讨厌的脚本之前保存全局变量。或者,您可以在 iframe 中加载脚本以隔离它的不良行为。
- 如果可能的话,最好只修改全局变量。脚本真的不应该触及它们,如果是,那可能是因为它们试图用 pollyfill 一些缺失的特性。脚本实际上对全局函数进行重大更改的情况很少见 - 但如果确实如此,向脚本作者提交错误报告以修复此行为可能是值得的。