Introduction
This particular tip gives you a very brief and easy way to handle the cross domain IFrame
communication.
Background
Recently, I joined MS Dynamics CRM team in my company.
There was a requirement in the project I was working - to place one IFrame
inside the CRM Form, which is in a different domain and push some data from IFrame
to Parent
window. But due to the same origin policy, it will not permit to get data from different domains. So, I searched a bit and followed some articles.
Finally, I came up with an answer, which is a Cross Browser solution. Let me explain that below.
Using the Code
We need to use window.postMessage for this task.
The syntax is:
window.postMessage(message, targetOrigin);
In the IFrame
We will write the below code to post/send a message to Parent
window/form.
window.parent.postMessage("Hello From IFrame", "*");
Note: Here '*' as targetOrigin parameter indicates no preference, otherwise you can specify the domain of Parent Window/the window to which message is posted like below:
window.parent.postMessage("Hello From IFrame", "http://example.com");
This targetOrigin
parameter is the domain of window to which the message is passed. If you have any port number associated with the Parent
window, then you need to mention that as well (For Example:- http://example.com:8080). This needs to be exactly correct, otherwise the message will not be posted.
In the Parent Window
We will write the below code to listen to the message posted by IFrame
.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function (e) {
alert(e.data);
}, false);
For Security
We should always send the targetOrigin
parameter as the Url of the target window/Parent window.
And we also need to check the origin of the event or Url of Originating window/IFrame. This is because any malicious website can send data or manipulate it.
So, the secure code of the receiver will look like below...
eventer(messageEvent, function (e) {
if (e.origin == 'http://iframe.example.com') {
alert(e.data);
}
}, false);
Here the domain of IFrame
/Origin of message posted is 'http://iframe.example.com'.
Points of Interest
You can do the reverse as well. That means you can pass message to the IFrame
from Parent
window and receive the same in IFrame
.
References
- window.postMessage
- Cross-document messaging
History
- 02 May 2013 - First version submitted for approval