2016-07-29 54 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兼容(在網站上,它可以不會在本地工作)。上傳完成後我會添加評論,然後運行我的測試。 –

相關問題