Skip to content

Instantly share code, notes, and snippets.

@makgithub
Last active April 5, 2017 10:05
Show Gist options
  • Save makgithub/5035df4b82110ada0c83d30abbf2dcc4 to your computer and use it in GitHub Desktop.
Save makgithub/5035df4b82110ada0c83d30abbf2dcc4 to your computer and use it in GitHub Desktop.
Send Message from Main page to Iframe url. SecurityError: Blocked a frame with origin from accessing a cross-origin frame. Accessing a cross-origin frame.
<!DOCTYPE html>
<html>
<head>
<title>My Iframe</title>
</head>
<body>
<button>Button</button>
<div id="childdiv"> </div>
<script type="text/javascript">
//To Recive the parent frame message
document.querySelector('button').onclick = function () {
parent.postMessage("myevent", "*")
};
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<iframe src="iframe.html" id="iframe" 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) {
alert('Message from iframe just came!');
console.log(e);
});
//send message to child window
window.onload = function () {
document.getElementById("iframe").contentWindow.postMessage(
'test message',
"*"
);
};
</script>
</body>
</html>
@makgithub
Copy link
Author

Two way iframe communication

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment