如何从iframe中调用主窗口中的函数

How to call function in main window from iframe?

本文关键字:窗口 函数 调用 iframe      更新时间:2023-09-26

首先,我知道这个问题与其他问题重复。但我试图做以下许多例子从许多问题在stackoverflow,但它没有工作。我不能从框架中调用主窗口的函数,但如果我使用框架标签,它的工作。

我试过了。

主窗口:

<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 

还有很多类似的形式

你有什么想法吗?还是我做错了什么?

看起来您正在直接从文件系统访问文件,如c:.....'page.html.

由于同源策略导致的错误,如果您将站点部署在tomcat或任何其他web服务器中,而不是从本地文件系统访问它,它应该工作,假设两个文件来自相同的域空间。

如果主页面(iframe)和iframe页面在同一个目录下,或者iframe页面是主页面目录的子目录,它将在FireFox中工作

以上将不工作在chrome,你需要启动chrome与标志--allow-file-access-from-files