Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. window.listen = function(cb) {
  2. // handle requests
  3. const recieveREQ = function(message) {
  4. if (message.data.type !== "REQ") {
  5. return;
  6. }
  7.  
  8. if (!(message.ports && message.ports[0])) {
  9. cb(new Error("ERROR 2315: connection request was malformed. No port."));
  10. return;
  11. }
  12.  
  13. message.ports[0].postMessage({ type: "REQ_ACK" });
  14.  
  15. cb(null, message.ports[0]);
  16. };
  17.  
  18. // listen for requests
  19. window.addEventListener("message", recieveREQ);
  20. };
  21.  
  22. window.connect = function(server, cb) {
  23. // Time out after 5s
  24. const timeout = setTimeout(function() {
  25. cb(new Error("ERROR 2200: timed out before getting a connection"));
  26. }, 5000);
  27.  
  28. const channel = new MessageChannel();
  29.  
  30. // Handle a response
  31. const recieveREQ_ACK = function(message) {
  32. console.log("BOIS", message);
  33. if (message.data.type !== "REQ_ACK") {
  34. console.log("oiajdsf");
  35. return;
  36. }
  37.  
  38. channel.port1.onmessage = null;
  39. clearTimeout(timeout);
  40. cb(null, channel.port1);
  41. };
  42.  
  43. // Listen for responses
  44. channel.port1.onmessage = recieveREQ_ACK;
  45.  
  46. // Request a connection
  47. server.postMessage({ type: "REQ" }, "*", [channel.port2]);
  48. };
  49.  
  50. /* USAGE:
  51.  
  52. // In the iframe
  53. connect(
  54. window.parent,
  55. function(err, port) {
  56. // Now I have this port to my parent.
  57. // I can port.onmessage, and port.postMessage.
  58. }
  59. );
  60.  
  61. // In the containing document (parent)
  62. listen(function(err, port) {
  63. // Same as above. Called when a client connects
  64. // and I can port.onmessage, and port.postMessage.
  65. });
  66.  
  67. */
  68.  
  69. // @aykev/@mrkev
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement