javascript - 如何从新的 iframe 重置损坏的 JavaScript 数组对象?
问题描述
我有一个在站点中运行的脚本,我不能指望它的window.Array
对象不会被覆盖。(它可能已被之前加载的另一个脚本更改)。
我创建了一个新的 iframe,我想将window.Array
对象设置回本机 Array 原型
// let's assume Array.prototype.filter function was changed by another script
Array.prototype.filter = ()=>{return "haha!"}
console.log('test overridden: ', new Array(1,2,3).filter(x=>x));
console.log('test overridden literal:', [1,2,3].filter(x=>x));
// prints test overridden: haha
// prints test overridden literal: haha
// get new window with native code from iframe
var iframe = null;
(iframe = document.createElement('iframe')).name = 'native_function';
document.body.appendChild(iframe);
var native = window.frames['native_function'];
// here I am trying to set my broken Array to a new fresh copy
Object.setPrototypeOf(Array, native.Array.prototype);
console.log('test restored filter: ', new Array(1,2,3).filter(x=>x));
console.log('test restored literal array filter', [1,2,3].filter(x=>x));
// prints test restored filter: haha
// prints test restored literal array filter: haha
// It didn't work.
如何将我的 window.Array 恢复为 native.window.Array ?
注意 我想将整个 Array 对象恢复为 iframe 窗口中的原始 Array。不仅是我刚刚用作示例的过滤器功能。
解决方案
我想将整个 Array 对象恢复为 iframe 窗口中的原始 Array
您无法覆盖从文字创建数组时使用的内置数组原型,因此您需要覆盖该原型上的方法。
const iframe = document.body.appendChild(document.createElement("iframe"));
const iframeArray = iframe.contentWindow.Array;
document.body.removeChild(iframe);
const nativeArrayProto = Object.getPrototypeOf([]);
for (const p of ["constructor", "filter", "map", "slice", /* … */])
nativeArrayProto[p] = iframeArray.prototype[p];
Array = nativeArrayProto.constructor;
Array.prototype = nativeArrayProto;
推荐阅读
- python-3.x - 在函数之间共享变量
- assembly - 在 yasm 中,当针对 32 位代码时,如何在 jmp 附近指定 16 位?
- c# - ReactiveUI 使用 WhenAny 观察 Collection 并分配 boolean PropertyHelper
- python - 使用 Pandas 或 SQL 根据订阅时长计算收入?
- javascript - Fs没有正确保存文件以及如何简化此代码
- android - 键盘隐藏后输入下的Android显示面板
- javascript - Ajax XMLHttpRequest.open 未被调用
- file - 如何在 Go 中获取文件的组 ID (GID)?
- xml - 等效于 xpath 选择器的 CSS 选择器
- android-studio - 我无法从 android studio 构建或运行我的颤振应用程序,但它可以从命令行运行