【问题标题】:Run JavaScript Function in a different HTML file inside a script tag在脚本标签内的不同 HTML 文件中运行 JavaScript 函数
【发布时间】:2016-07-29 01:29:19
【问题描述】:

目前我有两个 HTML 文件。一个名为 index.html,另一个名为 editor.html

在index.html里面我有一个editor.html的iframe 在这个iframe上面也是我做的一个通知系统。要运行通知,它使用我创建的函数,可以像这样使用:

Notification("msg");

当我从 index.html 内部调用它时,这个函数效果很好,因为该函数修改了 index.html 的 html 代码(通过 .innerHTML)。当我尝试从 editor.html 调用它时出现问题

即使在 index.html 的顶部像这样将 editor.html 添加到 index.html 中:

<script src="editor.html"></script>

我在 editor.html 中写了这个:

<script src="index.html"></script>

当我尝试从 editor.html 运行通知函数时出现错误,因为该函数在 index.html 中并修改了 index.html,不是 editor.html。

请记住,每个 index.html 和 editor.html 中的 javascript 都位于标签中,因为文件中还有其他 html。谢谢,如果您需要进一步确认,请提出问题。

【问题讨论】:

  • 一个页面永远不能直接在另一个页面上运行代码。他们只能使用Window.postMessage() 进行通信和传输数据。从 iframe 内部,将是 window.parent.postMessage(),从 iframe 外部是 document.querySelector('iframe').contentWindow.postMessage()。您还需要在任何接收页面上为“消息”事件附加一个事件侦听器。
  • 你能举一个使用单独的 index.html 和 editor.html 的例子吗?传递函数和参数的方法?

标签: javascript html tags


【解决方案1】:

如果 iframe 和容器在同一个域中,这可以正常工作。

您可以将 Notification 函数的定义放在一个外部文件中,例如 main.js:

function Notification( msg )
{
    var div = document.getElementById("notification-div") ;
    div.innerHTML = msg ;
    /* The important thing is make this to be the container window when
     * Notification is called, so document is the desired one.
     */
}

在 index.html 中你应该有 iframe 和一个 div 来打印通知文本:

<div id="notification-div"></div>
<iframe src="editor.html" width=300 height=200></iframe>

然后在 index.html 中包含 main.js:

<script type="text/javascript" src="main.js"></script>

在index.html中可以直接调用,只要是window即可:

Notification( "From index.html" ) ;
/* window will be this in the Notification function, so the call to
 * document.getElementById, will actually be window.document.getElementById
 */

在 editor.html 中,您可以将容器窗口对象称为顶部。所以这个调用会给出想要的结果:

top.Notification( "From editor.html" ) ;
/* top will be this in the Notification function, so the call to
 * document.getElementById, will actually be top.document.getElementById
 */

【讨论】:

  • 当我尝试此操作时,控制台中出现此错误消息,并且从 editor.html 运行通知不起作用,但从 index.html 运行通知。我仍然需要它从 editor.html 运行。这是错误:SecurityError: Blocked a frame with origin "null" from access a frame with origin "null".协议、域和端口必须匹配。
  • @AdamMikacich 您是否使用本地文件和 Chrome 进行测试?如果是这样,请尝试使用 Firefox 或 Edge 进行测试。
  • 我正在使用本地文件进行测试。我会把它上传到我的网站,看看它是否有效。顺便说一句,它必须与 Chrome 兼容(在网站上,虽然它不能在本地工作,但没关系)。上传完成后我会添加评论并运行我的测试。
  • @AdamMikacich 如果你想继续使用 Chrome 和本地文件进行测试,你也可以试试这个question 的答案。
  • 你太棒了!它在我的网站上效果很好!非常感谢!!!! :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-16
相关资源
最近更新 更多