javascript - 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);
这是为什么?
解决方案
这是因为:
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);
推荐阅读
- mysql - 如何让python从其他数据不完整的表中更新MYSQL?
- docker - 在 Docker 容器中访问 Kafka 代理
- jquery - 如何使用 JQuery AJAX 将模型传递给控制器?
- javascript - 如何使用 Vue 3 并添加插件 Boostrap-vue?
- laravel - Bulma 样式覆盖不起作用;使用 Laravel 7.25.0
- node.js - 是否可以使用 node.js passport.authenticate() 在 AWS api 网关中验证承载令牌?
- shopify - 按单位和重量销售 - Shopify
- react-native - react-native 中的 Flexbox 对齐问题
- python - python:将带有逗号和 $ 的数据框列转换为浮点数
- ios - @FetchRequest + 不区分大小写的排序 - SwiftUI 和 CoreData