Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Call Parent Window JavaScript Function inside iframe

Here is my code on http://my-localhost.com/iframe-test.html

<html>
<head><title>Welcome Iframe Test</title></head>
<body>
<iframe src="http://www.my-website.com/index.html" width="500" height="500"></iframe>
<script type="text/javascript">
function alertMyMessage(msg){
    alert(msg);
}
</script>
</body>
</html>

Here is code on http://www.my-website.com/index.html

<html>
<head></title>Welcome to my Server</title></head>
<body>
<h1>Welcome to My Server</ht>
<a href="javascript:void(0)" title="Click here" onClick="parent.alertMyMessage('Thanks for Helping me')">Click Here</a>
</body>
</html>

When i Click the "Click Here" Link. i got following Error.

Uncaught SecurityError: Blocked a frame with origin "http://www.my-website.com" from accessing a frame with origin "http://my-localhost.com". Protocols, domains, and ports must match.

Please Help me to Fix this Issue, or give some other solution for this.

like image 989
rkaartikeyan Avatar asked Oct 16 '13 14:10

rkaartikeyan


1 Answers

You can use postMessage!

PARENT

if (window.addEventListener) {
    window.addEventListener ("message", receive, false);        
}
else {
    if (window.attachEvent) {
        window.attachEvent("onmessage",receive, false);
    }
}

function receive(event){
    var data = event.data;
    if(typeof(window[data.func]) == "function"){
        window[data.func].call(null, data.params[0]);
    }
}

function alertMyMessage(msg){

    alert(msg);
}

IFRAME

function send(){
    window.parent.window.postMessage(
        {'func':'alertMyMessage','params':['Thanks for Helping me']},
        'http://www.my-website.com'
    );
}

REFERENCE

https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

like image 70
emilianoeloi Avatar answered Oct 21 '22 15:10

emilianoeloi