tabs-data.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /*
  2. * Copyright 2010-2019 Gildas Lormeau
  3. * contact : gildas.lormeau <at> gmail.com
  4. *
  5. * This file is part of SingleFile.
  6. *
  7. * SingleFile is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Lesser General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * SingleFile 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
  15. * GNU Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public License
  18. * along with SingleFile. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. /* global browser, singlefile */
  21. singlefile.tabsData = (() => {
  22. let persistentData, temporaryData;
  23. getPersistent().then(tabsData => persistentData = tabsData);
  24. return {
  25. onMessage,
  26. onTabRemoved,
  27. getTemporary,
  28. get: getPersistent,
  29. set: setPersistent
  30. };
  31. async function onMessage(message) {
  32. if (message.method.endsWith(".get")) {
  33. return getPersistent();
  34. }
  35. if (message.method.endsWith(".set")) {
  36. return setPersistent(message.tabsData);
  37. }
  38. }
  39. async function onTabRemoved(tabId) {
  40. delete temporaryData[tabId];
  41. const tabsData = await getPersistent();
  42. delete tabsData[tabId];
  43. setPersistent(tabsData);
  44. }
  45. function getTemporary(tabId) {
  46. if (!temporaryData) {
  47. temporaryData = {};
  48. }
  49. if (tabId !== undefined && !temporaryData[tabId]) {
  50. temporaryData[tabId] = {};
  51. }
  52. return temporaryData;
  53. }
  54. async function getPersistent(tabId) {
  55. if (!persistentData) {
  56. const config = await browser.storage.local.get();
  57. persistentData = config.tabsData || {};
  58. cleanup();
  59. }
  60. if (tabId !== undefined && !persistentData[tabId]) {
  61. persistentData[tabId] = {};
  62. }
  63. return persistentData;
  64. }
  65. async function setPersistent(tabsData) {
  66. persistentData = tabsData;
  67. await browser.storage.local.set({ tabsData });
  68. }
  69. async function cleanup() {
  70. if (persistentData) {
  71. const tabs = await browser.tabs.query({});
  72. Object.keys(persistentData).filter(key => {
  73. if (key != "autoSaveAll" && key != "autoSaveUnpinned" && key != "profileName") {
  74. return !tabs.find(tab => tab.id == key);
  75. }
  76. }).forEach(tabId => delete persistentData[tabId]);
  77. await browser.storage.local.set({ tabsData: persistentData });
  78. }
  79. }
  80. })();