Skip to content

Instantly share code, notes, and snippets.

@visioncan
Last active June 1, 2016 17:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save visioncan/2a924cfeed3516fa710ae8ac17d6c9c7 to your computer and use it in GitHub Desktop.
Save visioncan/2a924cfeed3516fa710ae8ac17d6c9c7 to your computer and use it in GitHub Desktop.
iframe cross domain communication
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Http</title>
</head>
<body>
<h1>http page</h1>
<iframe src="https://sub.domain.dev/https.html" frameborder="0" id="ff"></iframe>
<script>
var ut = {
listen: function (formDomain, fn) {
window.addEventListener('message', function (e) {
if(e.origin !== formDomain){ return; }
fn(e.data);
},false);
},
postMsg: function (t, msg, toDomain) {
return t.postMessage(msg, toDomain);
}
};
ut.listen('https://sub.domain.dev', function(data) {
console.log('@http Got msg = %s', data);
});
document.querySelector('#ff').onload = function (e) {
ut.postMsg(e.target.contentWindow, 'I am Http', 'https://sub.domain.dev');
};
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Https</title>
</head>
<body>
<h1>https page</h1>
<script>
var ut = {
listen: function (formDomain, fn) {
window.addEventListener('message', function (e) {
if(e.origin !== formDomain){ return; }
fn(e.data);
},false);
},
postMsg: function (t, msg, toDomain) {
return t.postMessage(msg, toDomain);
}
};
ut.postMsg(parent, 'I am https', 'http://www.domain.dev');
ut.listen('http://www.domain.dev', function (data) {
console.log('@https Got msg = %s', data);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment