首页 > 解决方案 > 在 iframe 中加载事件

问题描述

我试图在加载后在 iframe 中运行一些 javascript 并且遇到问题。我不确定这是否意味着我对正在发生的事情的概念是错误的,或者我的代码是否只是错误的。

我想要做的是在 iframe 环境中加载一个 javascript 文件,然后调用一个函数。(iframe 内容是使用单个文件捕获并从我的服务器提供的静态网页。我希望能够为 iframe 页面中的图像弹出菜单)。这是可能的,还是出于安全考虑而被阻止?我可以从 iframe 中获取 contentDocument 并查看其中的内容,但不对其进行任何更改。向 iframe 添加加载事件侦听器在顶级 DOM 中运行,而不是 iframe。

一个丑陋的解决方法是在我提供的每个 html 文件中添加一行加载脚本,但我不愿意这样做,因为它看起来有点脆弱。那是我唯一的选择吗?

标签: javascriptiframedom-events

解决方案


您可以选择 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);

推荐阅读