Reputation: 88
I'm Creating a Iframe dynamically on click of button using Javascript and displaying it in popup.
In the Iframe I'm loading another website(different domain) which consists of sequence of forms which takes user from first step to last step.
When the user is in last step he would be given a close button within the Iframe.
I want to close(hide) the popup containing Iframe on click of close button.
Is it Possible?Please help.
Upvotes: 1
Views: 1789
Reputation: 88
After hours of surfing the Web for finding solution I came across this soultion.
The Problem here is that the same-origin policy blocks scripts from accessing contents of site with other origin.
Actually origin consists of the following parts.
origin:<protocol(http/https)>://<hostname>:<port number>/path/to/page.html
The origin is considered to be different if protocol,hostname and port number are not same.In such cases you can not access the contents of one website from other website due to same-origin security policy.
In order to overcome it you have to use parent-child communication using window.postMessage().
FYI : https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage.
The Window.postMessage() method safely enables cross-origin communication.
Suppose that your parent website is example-parent.com and In Iframe your loading website example-iframe.com and let both are using http protocol.
Below is how I solved the problem.
In parent website add event listener for messages to receive as follows.
window.addEventListener('message',receiveMessage,false);
function receiveMessage(event){
var origin = event.origin || event.originalEvent.origin;
if(origin.indexOf('http://example-iframe.com')>=0) // check if message received from intended sender
{
if(event.data=="intended message format") // check if data received is in correct format
{
// call functionality that closes popup containing iframe
}else{ // data received is malacious
return;
}
}else{ // message is not received from intended sender
return;
}
}
From Iframe post message to the parent website as follows.
Post message syntax : otherWindow.postMessage(message, targetOrigin, [transfer]);
function sendMessage(){
parent.postMessage('intended message format','http://example-parent.com');
}
Use postMessage() properly,otherwise it may lead to cross-site scripting attack.
Upvotes: 3
Reputation: 783
As i understood correctly you want to call a function from child (close button in iframe) which closes the iframe. You can do this by call the parent
parent.myfunction() //call myfunction from parent
And in parent code you have to implement closing logic
myfunction() {
iframe.hide() //or whatever
}
Upvotes: 0