Instanceof fails in iframe [duplicate]

蓝咒 提交于 2019-12-10 16:21:31

问题


The following code returns true.

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

Doing the same in an <iframe> context returns false:

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

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

Demo

Why is that?


回答1:


This is because:

1) Element is actually window.Element

2) In JS there is no such thing as a "class". Everything (almost) is an object. So instanceof checks for Prototype ancestry. When you ask is some DOM node instanceof Element you could kind of translate this to someDOMNode.prototype === Element.

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

This will log true as expected:

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


来源:https://stackoverflow.com/questions/52222237/instanceof-fails-in-iframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!