简体   繁体   English

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

[英]How to call function in main window from iframe?

The first, i known this question it's duplicated with other questions. 首先,我知道这个问题与其他问题重复。 But i tried to do following many samples from many issues in stackoverflow but it didn't work. 但是我试图从stackoverflow的许多问题中跟踪许多样本,但是没有用。 I couldn't call function of main window from iframe but if i use frame tag it's work. 我无法从iframe调用主窗口的功能,但是如果我使用frame标签,那是可以的。

I tried like this. 我尝试过这样。

main window: 主窗口:

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

test.html test.html

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

Error messages from console. 来自控制台的错误消息。

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 

And many forms similar to this. 和许多与此类似的形式。

Do you have any ideas? 你有什么想法? or I did somethings wrong? 还是我做错了什么?

It looks like you are accessing the files from file system directly like c:.....\\page.html. 好像您是直接从文件系统访问文件一样,如c:..... \\ page.html。

The error because of the same origin policy , if you deploy the site in a tomcat or any other web server other than accessing it from local file system it should work, assuming both files are from the same domain space. 由于相同的原始策略而导致的错误,如果您将站点部署在tomcat或任何其他Web服务器中(而不是从本地文件系统访问它),则假定两个文件都来自相同的域空间,它应该可以工作。

If the main page(with iframe) and the iframe page is in the same directory or if the iframe page is a subdirectory of the main page directory it will work in FireFox . 如果主页(带有iframe)和iframe页面位于同一目录中,或者如果iframe页面是主页目录的子目录,则它将在FireFox中工作。

The above will not work in chrome you need to start chrome with the flag --allow-file-access-from-files 上面的方法不适用于chrome,您需要以--allow-file-access-from-files 标志启动chrome

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM