Skip to content

Instantly share code, notes, and snippets.

@anveo
Last active January 9, 2018 22:32
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 anveo/88965dd164ead2f70715e190fb82ffa8 to your computer and use it in GitHub Desktop.
Save anveo/88965dd164ead2f70715e190fb82ffa8 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<title>My Iframe</title>
</head>
<body>
<button>iframe</button>
<script type="text/javascript">
document.querySelector('button').onclick = function () {
parent.postMessage("myevent", "*")
};
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<iframe src="iframe.html" width="300" height="300"></iframe>
<script type="text/javascript">
var eventMethod = window.addEventListener
? "addEventListener"
: "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod === "attachEvent"
? "onmessage"
: "message";
eventer(messageEvent, function (e) {
// if (e.origin !== 'http://the-trusted-iframe-origin.com') return;
if (e.data === "myevent" || e.message === "myevent")
alert('Message from iframe just came!');
console.log(e);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment