Skip to content

Instantly share code, notes, and snippets.

@nesimtunc
Created December 7, 2015 05:08
Show Gist options
  • Save nesimtunc/cbfee61071ab46459b5c to your computer and use it in GitHub Desktop.
Save nesimtunc/cbfee61071ab46459b5c to your computer and use it in GitHub Desktop.
Communication between HTML DOM elements like iframe in a secure way
// Let's assume you have two separated HTML DOM elements that
// you want to make a secure communication between them
// ex: an iframe inside HTML body
// since cross domain restrictions you may not access the iframe object
// here is how you can manage it (of course if you develop both side)
// This code has been developed regarding this document:
// https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
// Main Page (index.html)
// Here is our HTML element
// <iframe id="chat" src="http://chat.example.com/" ... />
<script>
var timer;
$(document).ready(function e() {
timer = setInterval(function e() {
checkRoom();
}, 1000);
});
$(document).unload(function e() {
if (timer)
clearInterval(timer);
});
function checkRoom() {
if (document.getElementById("chat") != undefined) {
// let's send our message to iframe element
// you can send JSON object as well
chat.postMessage({ request: "getRoom" }, "*");
}
}
// When we receive message back (or for general requests)
function receiveMessageFromChat(event) {
// additional security precaution
if (!(/^https:\/\/(.*)\.(example\.net|example\.com)$/.test(event.origin))) {
return;
}
if (typeof event.data != "object") {
return;
}
var request = event.data.request;
var response = event.data.response;
if (!request || !response) {
return;
}
if (request == "getRoom") {
// do your action right here
}
}
// bind to 'message' event of the element
window.addEventListener("message", receiveMessageFromChat, false);
</script>
// Chat Page (chat.html)
<script>
function receiveMessageFromMainPage(event) {
if (!(/^https:\/\/(.*)\.(example\.net|example\.com)$/.test(event.origin))) {
return;
}
if (typeof event.data != "object") {
return;
}
var request = event.data.request;
if (!request) {
return;
}
if (request == "getRoom") {
// send response back to Main Page
// you can send JSON object as well
var currentRoom = $.connection.chat.state.activeRoom;
event.source.postMessage({
request: event.data.request,
response: currentRoom
}, event.origin);
event.stopImmediatePropagation();
return true;
}
}
// bind to 'message' event of the element
window.addEventListener("message", receiveMessageFromMainPage, false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment