In doing a postMessage/addEventListener/receiveMessage messaging means in JavaScript between an iFrame's contents and the page the iFrame itself sits in which is hosted at a different domain name, one may let the iFrame know what domain name is poking at it (a vital piece of information) by talking from the outside to the inside first as seen here or alternatively by handing that data in at the URL line when calling the iFrame content's.
<!DOCTYPE html>
<html>
<body>
<script context="text/javascript">
function receiveMessage(event) {
if (event.origin == "http://bar") {
alert(event.data);
}
};
window.addEventListener("message", receiveMessage, false);
</script>
<p>This page holds an iframe at: "foo"</p>
<iframe name="eye" src="http://bar/index.html?whoisoutside=foo">
</iframe>
</body>
</html>
Make sense of what was handed in like so.
<!DOCTYPE html>
<html>
<body>
<script context="text/javascript">
var urlVariables = window.location.href.substring(window.location.href.indexOf('?')
+ 1, window.location.href.length);
var whoIsOutside;
var cat = {
name: "Patches",
color: "Calico",
about: function() {
return this.name + " is " + this.color;
}
};
function findWhoIsOutside(segment) {
if (urlVariables.indexOf('=') == -1)
{
return null;
} else {
var name = segment.substring(0, segment.indexOf('='));
if(name.toLowerCase() == "whoisoutside") {
return segment.substring(segment.indexOf('=') + 1, segment.length);
} else {
return null;
}
}
};
while (whoIsOutside === undefined) {
if (urlVariables.indexOf('&') == -1)
{
whoIsOutside = findWhoIsOutside(urlVariables);
} else {
var attemptToMatch = findWhoIsOutside(urlVariables.substring(0,
urlVariables.indexOf('&')));
urlVariables = urlVariables.substring(urlVariables.indexOf('&') + 1,
urlVariables.length);
if (attemptToMatch) {
whoIsOutside = attemptToMatch;
}
}
};
top.postMessage(cat.about(), "http://" + whoIsOutside);
</script>
<p>This page sits inside an iframe at: "bar"</p>
</body>
</html>
The second page here is the page inside of the iFrame and the first page is the page that actually holds the iFrame. The first page lives at http://foo/index.html and the second page lives at http://bar/index.html in this example. The second page will hand the string made by cat.about() up to the first page which will then cough it up to view in an alert.
No comments:
Post a Comment