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.

NetworkInfoService.web.ts 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import EventEmitter from 'events';
  2. import { ONLINE_STATE_CHANGED_EVENT } from './events';
  3. /**
  4. * The network info service implementation for web (Chrome, Firefox and Safari).
  5. */
  6. export default class NetworkInfoService extends EventEmitter {
  7. _onlineStateListener: any;
  8. _offlineStateListener: any;
  9. /**
  10. * Creates new instance...
  11. */
  12. constructor() {
  13. super();
  14. this._onlineStateListener = this._handleOnlineStatusChange.bind(this, /* online */ true);
  15. this._offlineStateListener = this._handleOnlineStatusChange.bind(this, /* offline */ false);
  16. }
  17. /**
  18. * Callback function to track the online state.
  19. *
  20. * @param {boolean} isOnline - Is the browser online or not.
  21. * @private
  22. * @returns {void}
  23. */
  24. _handleOnlineStatusChange(isOnline: boolean) {
  25. this.emit(ONLINE_STATE_CHANGED_EVENT, { isOnline });
  26. }
  27. /**
  28. * Checks for support.
  29. *
  30. * @returns {boolean}
  31. */
  32. static isSupported() {
  33. return Boolean(window.addEventListener) && typeof navigator.onLine !== 'undefined';
  34. }
  35. /**
  36. * Starts the service.
  37. *
  38. * @returns {void}
  39. */
  40. start() {
  41. window.addEventListener('online', this._onlineStateListener);
  42. window.addEventListener('offline', this._offlineStateListener);
  43. }
  44. /**
  45. * Stops the service.
  46. *
  47. * @returns {void}
  48. */
  49. stop() {
  50. window.removeEventListener('online', this._onlineStateListener);
  51. window.removeEventListener('offline', this._offlineStateListener);
  52. }
  53. }