Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instanceof fails in iframe [duplicate]

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?

like image 758
Zenoo Avatar asked Jan 27 '23 11:01

Zenoo


1 Answers

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);
like image 157
Sergiu Paraschiv Avatar answered Jan 31 '23 22:01

Sergiu Paraschiv