offlineClient.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. "use strict";
  2. (function() {
  3. class OfflineClient
  4. {
  5. constructor()
  6. {
  7. // Create a BroadcastChannel, if supported.
  8. this._broadcastChannel = (typeof BroadcastChannel === "undefined" ? null : new BroadcastChannel("offline"));
  9. // Queue of messages received before a message callback is set.
  10. this._queuedMessages = [];
  11. // The message callback.
  12. this._onMessageCallback = null;
  13. // If BroadcastChannel is supported, listen for messages.
  14. if (this._broadcastChannel)
  15. this._broadcastChannel.onmessage = (e => this._OnBroadcastChannelMessage(e));
  16. }
  17. _OnBroadcastChannelMessage(e)
  18. {
  19. // Have a message callback set: just forward the call.
  20. if (this._onMessageCallback)
  21. {
  22. this._onMessageCallback(e);
  23. return;
  24. }
  25. // Otherwise the app hasn't loaded far enough to set a message callback.
  26. // Buffer the incoming messages to replay when the app sets a callback.
  27. this._queuedMessages.push(e);
  28. }
  29. SetMessageCallback(f)
  30. {
  31. this._onMessageCallback = f;
  32. // Replay any queued messages through the handler, then clear the queue.
  33. for (let e of this._queuedMessages)
  34. this._onMessageCallback(e);
  35. this._queuedMessages.length = 0;
  36. }
  37. };
  38. // Create the offline client ASAP so we receive and start queueing any messages the SW broadcasts.
  39. window.OfflineClientInfo = new OfflineClient();
  40. }());