iframe中的Instanceof失败 [英] Instanceof fails in iframe

查看:179
本文介绍了iframe中的Instanceof失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码返回 true

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

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

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

为什么会这样?

推荐答案

这是因为:

1)元素实际上是 window.Element

2)在JS中没有类这样的东西。一切(差不多)都是一个对象。因此,检查 Prototype ancestry 的实例。当您询问是某个DOM节点instanceof Element 时,您可以将其转换为 someDOMNode.prototype === 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 !! !

这将按预期记录 true

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

这篇关于iframe中的Instanceof失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆