简体   繁体   中英

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. I couldn't call function of main window from iframe but if i use frame tag it's work.

I tried like this.

main window:

<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>

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.

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.

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 .

The above will not work in chrome you need to start chrome with the flag --allow-file-access-from-files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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