我在 Hook appendChild 时遇到了一个非常奇怪的竞争条件。 考虑这段代码:
var RealAppend = IframeWindow.Element.prototype.appendChild;
IframeWindow.Element.prototype.appendChild = function(){
RealAppend.apply(this, arguments); //some more code here --- >};
我正在挂接一些 iframe appendchild,这就是为什么我使用 IframeWindow 作为 iframe 内容窗口执行“IframeWindow.Element.prototype.appendChild”。
现在,在我挂接 appendchild 之后,我开始将节点附加到 iframe ,其中一个节点是一个带有 id="somediv"的简单 div 元素,另一个节点是一个 javascript 元素,一旦 javascript执行后,它将使用 document.createElement
创建一个 iframe 并设置其属性,然后执行 document.getElementById('somediv').appendChild(CreatedIframe);
这会将创建的 iframe 附加到“somediv”,我的目标是拦截最后一个 appendchild 并 Hook 该 iframe 的 appendchild。
现在首先我想也许我需要像这样重写 appendchild:
someDiv.appendChild = function(){.....
但经过更多测试后,我发现有时我的代码确实成功并 Hook 了最后一个 iframe,有时 SomeDiv.appendChild
是 native 代码而我的代码失败了。
有什么想法吗?
编辑: 我认为这可能与我正在使用
document.createRange().createContextualFragment(strHTML);
}
将 html 解析为字符串,然后将节点附加到 iframe,因此 div (somediv) 可能从那里获得一个干净的 appendChild?但为什么有时有效有时无效? 另一件事是,在页面加载后,我使用开发工具获取 somediv.appendchild 我每次都得到钩子(Hook)代码,所以只有当 javascript 代码执行时才会出现问题
最佳答案
所以我设法找出问题所在,所以如果有人遇到这个问题,这里是解决方案: 当我将 html 字符串解析到节点以便我可以将它们附加到 iframe 时,我首先使用“DOMParser”API,但我错过了 DOMParser 使用来自调用者 contentWindow 的文档的事实,而不是像这样调用 DOMParser:
new DOMParser();
我需要这样调用它:
new HookedIframeContentWindow.DOMParser();
关于javascript - Hook appendChild 时的竞争条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51764716/