2013-03-15 78 views
0

第一,我知道這個問題與其他問題重複。但我試圖做以下很多來自stackoverflow中的許多問題的示例,但它沒有奏效。我無法從iframe調用主窗口的功能,但是如果我使用框架標記,它是可行的。如何從iframe調用主窗口中的函數?

我試過這樣。

主窗口:

<body> 
<iframe src='test.html'></iframe> 
<script>    
    var alertFunc = function(){ 
     window.alert("work!"); 
    } 
</script> 
</body> 

的test.html從控制檯

<body> 
    <input type="button" onclick="window.parent.alertFunc();" value="Test" /> 
</body> 

錯誤消息。

Unsafe JavaScript attempt to access frame with URL file:///C:/.../index.html from frame with URL file:///C:/.../test.html. Domains, protocols and ports must match. 
test.html:30 
Uncaught TypeError: Cannot call method 'alertFunc' of undefined 

和許多形式類似。

你有什麼想法嗎?或者我做錯了什麼?

+0

試試這個: http://stackoverflow.com/questions/2161388/iframe-function-calling-from-iframe- to-parent-page-javascript-function – blackpg 2013-03-15 02:43:42

+0

檢查您的瀏覽器控制檯是否有任何錯誤 – 2013-03-15 02:51:17

+0

@Arun P Johny其錯誤更新爲 – fronthem 2013-03-15 02:59:24

回答

0

它看起來像你直接從文件系統訪問文件,如c:..... \ page.html。

由於same origin policy的錯誤,如果您將該站點部署在tomcat或任何其他Web服務器上,而不是從本地文件系統訪問它,它應該可以工作,假定這兩個文件來自同一個域空間。

如果主頁面(與iframe)和iframe頁面位於同一目錄中,或者iframe頁面是主頁面目錄的子目錄,則它將在FireFox中運行。

以上將無法在Chrome中工作,你需要start chrome with the flag--allow-file-access-from-files

+0

,但是我將此應用程序作爲離線應用程序。我該如何解決這個問題? – fronthem 2013-03-15 03:09:19

+0

這是瀏覽器使用? – 2013-03-15 03:12:44

+0

我用Chrome .. – fronthem 2013-03-15 03:27:39

相關問題