/static/iframe.html

http://github.com/biilmann/eventsource-broker · HTML · 54 lines · 47 code · 7 blank · 0 comment · 0 complexity · cc7deb361cadddb32223a0ef3ae8c285 MD5 · raw file

  1. <!doctype html>
  2. <head><title>EventSource IFrame</title></head>
  3. <script>
  4. if (typeof(window.addEventListener) == "undefined") {
  5. window.addEventListener = function(name, fn) {
  6. window.attachEvent("on" + name, fn);
  7. };
  8. }
  9. </script>
  10. <script src="/static/eventsource.polyfill.js"></script>
  11. <script>
  12. var channel = document.location.search.match(/channel=([^&]+)/)[1];
  13. var socket = document.location.search.match(/socket=([^&]+)/)[1];
  14. var post = function(path, data, callback) {
  15. var xhr = new XMLHttpRequest();
  16. xhr.open('POST', path, true);
  17. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  18. if (callback) {
  19. xhr.onreadystatechange = callback;
  20. }
  21. xhr.send(data);
  22. };
  23. setTimeout(function() {
  24. // on success
  25. var evtSrc = new EventSource( "/eventsource?socket=" + socket );
  26. if (evtSrc.readyState > 0) {
  27. parent.postMessage('{"eshqEvent":"open", "channel": "' + channel +'"}', "*");
  28. } else {
  29. evtSrc.onopen = function(e) {
  30. parent.postMessage('{"eshqEvent":"open", "channel": "' + channel +'"}', "*");
  31. };
  32. }
  33. evtSrc.onerror = function(e) {
  34. parent.postMessage('{"eshqEvent":"error", "channel": "' + channel +'"}', "*");
  35. };
  36. evtSrc.onmessage = function(e) {
  37. parent.postMessage(JSON.stringify({
  38. eshqEvent: "message",
  39. originalEvent: e,
  40. channel: channel
  41. }), "*");
  42. };
  43. }, 0);
  44. window.addEventListener("message", function(e) {
  45. post("/socket/" + socket, "data=" + encodeURIComponent(e.data));
  46. }, false);
  47. </script>