2016-07-29 49 views
0

目前我有两个HTML文件。一个名为index.html,另一个名为editor.html在脚本标记内的不同HTML文件中运行JavaScript函数

Inside index.html我有一个iframe的editor.html上面这个iframe也是我制作的通知系统。要运行它使用我创建了一个功能的通知,可以使用像这样:当我把它在index.html内

Notification("msg"); 

此功能的伟大工程,因为函数修改的index.html的HTML代码(通过.innerHTML)。一个问题显示出来,当我试图从editor.html

即使有editor.html加入到这样的index.html在index.html的顶部叫它:

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

我写这在editor.html:

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

当我尝试并运行editor.html通知功能有一个错误,因为该功能是index.html的内部和修改的index.html,编辑器html的。

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

+2

一个页面不能直接在另一个页面上运行代码。他们只能使用['Window.postMessage()'](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage)进行通信和传输数据。从iframe内部,这将是'window.parent.postMessage()',并从iframe外的document.querySelector('iframe')。contentWindow.postMessage()'。您还需要在任何接收页面上附加“消息”事件的事件侦听器。 – Siguza

+0

你可以举个例子使用独立的index.html和editor.html吗?一种传递函数和参数的方法? –

回答

1

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

你可以把通知功能的定义在一个外部文件,像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中可以直接调用它,只要这个窗口:

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 
*/ 
+0

当我尝试这个时,这个错误消息出现在控制台中,并且从editor.html运行一个通知无效,但是从index.html它没有。我仍然**需要**它从editor.html运行。以下是错误:SecurityError:阻止了一个源“null”的框架访问源“null”的框架。协议,域和端口必须匹配。 –

+0

@AdamMikacich你使用本地文件和Chrome进行测试吗?如果是这样,请尝试使用Firefox或Edge进行测试。 – 2016-07-29 03:40:27

+0

我正在测试本地文件。我会将其上传到我的网站,看看它是否有效。顺便说一句,它是**必须**,这是与Chrome兼容(在网站上,它可以不会在本地工作)。上传完成后我会添加评论,然后运行我的测试。 –

相关问题