Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement