tabs-data.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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.getTabsData) {
  33. return getPersistent();
  34. }
  35. if (message.setTabsData) {
  36. return setPersistent(message.tabsData);
  37. }
  38. }
  39. async function onTabRemoved(tabId) {
  40. const tabsData = await getPersistent();
  41. delete tabsData[tabId];
  42. setPersistent(tabsData);
  43. }
  44. function getTemporary(tabId) {
  45. if (!temporaryData) {
  46. temporaryData = {};
  47. }
  48. if (tabId !== undefined && !temporaryData[tabId]) {
  49. temporaryData[tabId] = {};
  50. }
  51. return temporaryData;
  52. }
  53. async function getPersistent(tabId) {
  54. if (!persistentData) {
  55. const config = await browser.storage.local.get();
  56. persistentData = config.tabsData || {};
  57. cleanup();
  58. }
  59. if (tabId !== undefined && !persistentData[tabId]) {
  60. persistentData[tabId] = {};
  61. }
  62. return persistentData;
  63. }
  64. async function setPersistent(tabsData) {
  65. persistentData = tabsData;
  66. await browser.storage.local.set({ tabsData });
  67. }
  68. async function cleanup() {
  69. if (persistentData) {
  70. const tabs = await browser.tabs.query({});
  71. Object.keys(persistentData).filter(key => {
  72. if (key != "autoSaveAll" && key != "autoSaveUnpinned" && key != "profileName") {
  73. return !tabs.find(tab => tab.id == key);
  74. }
  75. }).forEach(tabId => delete persistentData[tabId]);
  76. await browser.storage.local.set({ tabsData: persistentData });
  77. }
  78. }
  79. })();