lazy-timeout.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright 2010-2020 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * The code in this file is free software: you can redistribute it and/or
  8. * modify it under the terms of the GNU Affero General Public License
  9. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  10. * of the License, or (at your option) any later version.
  11. *
  12. * The code in this file is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  15. * General Public License for more details.
  16. *
  17. * As additional permission under GNU AGPL version 3 section 7, you may
  18. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  19. * AGPL normally required by section 4, provided you include this license
  20. * notice and a URL through which recipients can access the Corresponding
  21. * Source.
  22. */
  23. /* global browser, setTimeout, clearTimeout */
  24. (() => {
  25. "use strict";
  26. const timeouts = new Map();
  27. browser.runtime.onMessage.addListener((message, sender) => {
  28. if (message.method == "singlefile.lazyTimeout.setTimeout") {
  29. let tabTimeouts = timeouts.get(sender.tab.id);
  30. if (tabTimeouts) {
  31. const previousTimeoutId = tabTimeouts.get(message.type);
  32. if (previousTimeoutId) {
  33. clearTimeout(previousTimeoutId);
  34. }
  35. }
  36. const timeoutId = setTimeout(async () => {
  37. try {
  38. const tabTimeouts = timeouts.get(sender.tab.id);
  39. if (tabTimeouts) {
  40. deleteTimeout(tabTimeouts, sender.tab.id, message.type);
  41. }
  42. await browser.tabs.sendMessage(sender.tab.id, { method: "singlefile.lazyTimeout.onTimeout", type: message.type });
  43. } catch (error) {
  44. // ignored
  45. }
  46. }, message.delay);
  47. if (!tabTimeouts) {
  48. tabTimeouts = new Map();
  49. timeouts.set(sender.tab.id, tabTimeouts);
  50. }
  51. tabTimeouts.set(message.type, timeoutId);
  52. return Promise.resolve({});
  53. }
  54. if (message.method == "singlefile.lazyTimeout.clearTimeout") {
  55. let tabTimeouts = timeouts.get(sender.tab.id);
  56. if (tabTimeouts) {
  57. const timeoutId = tabTimeouts.get(message.type);
  58. if (timeoutId) {
  59. clearTimeout(timeoutId);
  60. }
  61. deleteTimeout(tabTimeouts, sender.tab.id, message.type);
  62. }
  63. return Promise.resolve({});
  64. }
  65. });
  66. browser.tabs.onRemoved.addListener(tabId => timeouts.delete(tabId));
  67. function deleteTimeout(tabTimeouts, tabId, type) {
  68. tabTimeouts.delete(type);
  69. if (!tabTimeouts.size) {
  70. timeouts.delete(tabId);
  71. }
  72. }
  73. })();