问题
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