refresh.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /* eslint-disable */
  2. (function () {
  3. 'use strict';
  4. // This is the custom ID for HMR (chrome-extension/vite.config.mts)
  5. const __HMR_ID = 'chrome-extension-hmr';
  6. const LOCAL_RELOAD_SOCKET_PORT = 8081;
  7. const LOCAL_RELOAD_SOCKET_URL = `ws://localhost:${LOCAL_RELOAD_SOCKET_PORT}`;
  8. const DO_UPDATE = 'do_update';
  9. const DONE_UPDATE = 'done_update';
  10. class MessageInterpreter {
  11. // eslint-disable-next-line @typescript-eslint/no-empty-function
  12. constructor() {}
  13. static send(message) {
  14. return JSON.stringify(message);
  15. }
  16. static receive(serializedMessage) {
  17. return JSON.parse(serializedMessage);
  18. }
  19. }
  20. function initClient({ id, onUpdate }) {
  21. const ws = new WebSocket(LOCAL_RELOAD_SOCKET_URL);
  22. ws.onopen = () => {
  23. ws.addEventListener('message', event => {
  24. const message = MessageInterpreter.receive(String(event.data));
  25. if (message.type === DO_UPDATE && message.id === id) {
  26. onUpdate();
  27. ws.send(MessageInterpreter.send({ type: DONE_UPDATE }));
  28. return;
  29. }
  30. });
  31. };
  32. }
  33. function addRefresh() {
  34. let pendingReload = false;
  35. initClient({
  36. id: __HMR_ID,
  37. onUpdate: () => {
  38. // disable reload when tab is hidden
  39. if (document.hidden) {
  40. pendingReload = true;
  41. return;
  42. }
  43. reload();
  44. },
  45. });
  46. // reload
  47. function reload() {
  48. pendingReload = false;
  49. window.location.reload();
  50. }
  51. // reload when tab is visible
  52. function reloadWhenTabIsVisible() {
  53. !document.hidden && pendingReload && reload();
  54. }
  55. document.addEventListener('visibilitychange', reloadWhenTabIsVisible);
  56. }
  57. addRefresh();
  58. })();