Last active
March 18, 2019 19:20
-
-
Save mrkev/d290f6015c2553f1fb5114d5fefcc639 to your computer and use it in GitHub Desktop.
Easy two-way communication between two different JavaScript contexts (ie, iframe <-> parent window).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.listen = function(cb) { | |
// handle requests | |
const recieveREQ = function(message) { | |
if (message.data.type !== "REQ") { | |
return; | |
} | |
if (!(message.ports && message.ports[0])) { | |
cb(new Error("ERROR 2315: connection request was malformed. No port.")); | |
return; | |
} | |
message.ports[0].postMessage({ type: "REQ_ACK" }); | |
cb(null, message.ports[0]); | |
}; | |
// listen for requests | |
window.addEventListener("message", recieveREQ); | |
}; | |
window.connect = function(server, cb) { | |
// Time out after 5s | |
const timeout = setTimeout(function() { | |
cb(new Error("ERROR 2200: timed out before getting a connection")); | |
}, 5000); | |
const channel = new MessageChannel(); | |
// Handle a response | |
const recieveREQ_ACK = function(message) { | |
console.log("BOIS", message); | |
if (message.data.type !== "REQ_ACK") { | |
console.log("oiajdsf"); | |
return; | |
} | |
channel.port1.onmessage = null; | |
clearTimeout(timeout); | |
cb(null, channel.port1); | |
}; | |
// Listen for responses | |
channel.port1.onmessage = recieveREQ_ACK; | |
// Request a connection | |
server.postMessage({ type: "REQ" }, "*", [channel.port2]); | |
}; | |
/* USAGE: | |
// In the iframe | |
connect( | |
window.parent, | |
function(err, port) { | |
// Now I have this port to my parent. | |
// I can port.onmessage, and port.postMessage. | |
} | |
); | |
// In the containing document (parent) | |
listen(function(err, port) { | |
// Same as above. Called when a client connects | |
// and I can port.onmessage, and port.postMessage. | |
}); | |
*/ | |
// @aykev/@mrkev |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment