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.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. // @ts-ignore
  34. return window.addEventListener && typeof navigator.onLine !== 'undefined';
  35. }
  36. /**
  37. * Starts the service.
  38. *
  39. * @returns {void}
  40. */
  41. start() {
  42. window.addEventListener('online', this._onlineStateListener);
  43. window.addEventListener('offline', this._offlineStateListener);
  44. }
  45. /**
  46. * Stops the service.
  47. *
  48. * @returns {void}
  49. */
  50. stop() {
  51. window.removeEventListener('online', this._onlineStateListener);
  52. window.removeEventListener('offline', this._offlineStateListener);
  53. }
  54. }