javascript - 在 iframe 中加载事件
问题描述
我试图在加载后在 iframe 中运行一些 javascript 并且遇到问题。我不确定这是否意味着我对正在发生的事情的概念是错误的,或者我的代码是否只是错误的。
我想要做的是在 iframe 环境中加载一个 javascript 文件,然后调用一个函数。(iframe 内容是使用单个文件捕获并从我的服务器提供的静态网页。我希望能够为 iframe 页面中的图像弹出菜单)。这是可能的,还是出于安全考虑而被阻止?我可以从 iframe 中获取 contentDocument 并查看其中的内容,但不对其进行任何更改。向 iframe 添加加载事件侦听器在顶级 DOM 中运行,而不是 iframe。
一个丑陋的解决方法是在我提供的每个 html 文件中添加一行加载脚本,但我不愿意这样做,因为它看起来有点脆弱。那是我唯一的选择吗?
解决方案
您可以选择 iframe 元素并访问其内部窗口对象。为此,首先为您的iframe
元素分配一个 id
<iframe id="chosen-iframe" ...></iframe>
并访问窗口使用以下
const iframe = document.getElementById('chosen-iframe');
const iFrameWindowElement = iframe.contentWindow;
通过访问窗口,您可以创建一个脚本标签,其中包含要在 iframe 中注入的脚本
var injectedScript = iFrameWindowElement.document.createElement("script");
injectedScript.append(...);
iFrameWindowElement.document.documentElement.appendChild(script);
推荐阅读
- c# - 远程服务器返回错误:(550) .NET 中的文件不可用(例如,找不到文件,无法访问)
- sql - 如何从控制器的循环中返回错误?
- html - 如何正确使用关键帧动画?
- powershell - 如何使用 PowerShell 验证 Office 365 电子邮件 DNS 条目
- docker - Docker 注册表“错误授权上下文”
- python - 将两个不同的 Sklearn 分类器应用于相同数据的两个不同子集
- mongodb - MongoDB查询仅查找匹配的嵌套数组
- oop - 使用 C# 9.0 记录构建类似智能枚举/区分联合/总和类型的数据结构?
- javascript - 如何阻止 javascript 函数使用 CSP?
- python - Pandas 读取列标题由 ; 分隔的 CSV 文件