首页 > 解决方案 > iframe 中的 Instanceof 失败

问题描述

以下代码返回true.

console.log(document.createElement('script') instanceof Element);


在上下文中执行相同操作会<iframe>返回false

let iframe = document.querySelector('iframe');
iframe = iframe.contentDocument || iframe.contentWindow.document;

console.log(iframe.createElement('script') instanceof Element);

演示

这是为什么?

标签: javascriptiframeinstanceof

解决方案


这是因为:

1)Element实际上是window.Element

2)在 JS 中没有“类”这样的东西。一切(几乎)都是一个对象。所以 instanceof 检查Prototype ancestry。当您询问时,is some DOM node instanceof Element您可以将其翻译成someDOMNode.prototype === Element.

3)window.Element !== document.querySelector('iframe').contentWindow.Element!!!

这将按true预期记录:

console.log(iframe.createElement('script') instanceof  document.querySelector('iframe').contentWindow.Element);

推荐阅读