This library provides an easy way to send events to a web browser (or any other client) over HTTP.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

client.js 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. (function() {
  2. function post(url, cb) {
  3. var xhr = new XMLHttpRequest();
  4. let timeout = setTimeout(function() {
  5. console.log("Timed out, aborting.");
  6. xhr.abort();
  7. }, 3000);
  8. xhr.addEventListener("load", function() {
  9. clearTimeout(timeout);
  10. try {
  11. var obj = JSON.parse(xhr.responseText);
  12. } catch (err) {
  13. console.log(xhr.responseText);
  14. cb(err);
  15. }
  16. if (obj.error) {
  17. cb(obj.error);
  18. } else {
  19. cb(null, obj);
  20. }
  21. });
  22. xhr.addEventListener("error", function(err) {
  23. clearTimeout(timeout);
  24. cb(err);
  25. });
  26. xhr.addEventListener("abort", function(err) {
  27. clearTimeout(timeout);
  28. cb(err);
  29. });
  30. xhr.open("POST", url);
  31. xhr.send();
  32. }
  33. window.WebEvents = function() {
  34. var self = {};
  35. var cbs = {};
  36. var key = null;
  37. function emit(name, args) {
  38. if (!cbs[name])
  39. return;
  40. cbs[name].forEach(function(cb) {
  41. cb(args);
  42. });
  43. }
  44. function init() {
  45. console.log("init...");
  46. post("/webevents/register", function(err, res) {
  47. console.log("Init done,", err ? "with errors" : "no errors");
  48. // Retry on error
  49. if (err) {
  50. console.log(err);
  51. setTimeout(function() { init() }, 2000);
  52. return;
  53. }
  54. emit("connection");
  55. key = res.key;
  56. await();
  57. });
  58. }
  59. function await() {
  60. post("/webevents/await/"+key, function(err, res) {
  61. if (err) {
  62. console.log("Await done, with errors");
  63. }
  64. // Retry on error
  65. if (err === "ENOTREGISTERED") {
  66. console.log("Not registered, reregistering");
  67. setTimeout(function() { init() }, 2000);
  68. return;
  69. } else if (err) {
  70. console.error(err);
  71. setTimeout(function() { await() }, 2000);
  72. return;
  73. }
  74. res.forEach(function(evt) {
  75. emit(evt.name, evt.args);
  76. });
  77. await();
  78. });
  79. }
  80. self.on = function(name, cb) {
  81. if (!cbs[name])
  82. cbs[name] = [];
  83. cbs[name].push(cb);
  84. };
  85. init();
  86. return self;
  87. }
  88. })();