settings.js 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /**
  2. * FeHelper Settings Tools
  3. * @author zhaoxianlie
  4. */
  5. import Awesome from '../background/awesome.js';
  6. export default (() => {
  7. // 所有配置项
  8. let optionItemsWithDefaultValue = {
  9. 'OPT_ITEM_CONTEXTMENUS': true,
  10. 'JSON_PAGE_FORMAT': true,
  11. 'FORBID_OPEN_IN_NEW_TAB': false,
  12. 'AUTO_DARK_MODE': false,
  13. 'ALWAYS_DARK_MODE': false,
  14. 'CONTENT_SCRIPT_ALLOW_ALL_FRAMES': false,
  15. 'FORBID_STATISTICS': false
  16. };
  17. /**
  18. * 获取全部配置项
  19. * @returns {string[]}
  20. * @private
  21. */
  22. let _getAllOpts = () => Object.keys(optionItemsWithDefaultValue);
  23. /**
  24. * 提取配置项
  25. * @param {Function} callback 回调方法
  26. */
  27. let _getOptions = function (callback) {
  28. let rst = {};
  29. chrome.storage.local.get(_getAllOpts(),(objs) => {
  30. // 确保objs是一个对象
  31. objs = objs || {};
  32. // 遍历所有配置项,确保每个配置项都有值
  33. _getAllOpts().forEach(item => {
  34. if (objs.hasOwnProperty(item) && objs[item] !== null) {
  35. rst[item] = objs[item];
  36. } else {
  37. // 使用默认值
  38. rst[item] = optionItemsWithDefaultValue[item];
  39. }
  40. });
  41. callback && callback.call(null, rst);
  42. });
  43. };
  44. /**
  45. * 保存配置
  46. * @param items
  47. * @param callback
  48. * @private
  49. */
  50. let _setOptions = function (items, callback) {
  51. // 确保items是数组类型
  52. if (!Array.isArray(items)) {
  53. // 如果传入的是对象类型,转换为数组形式
  54. if (typeof items === 'object' && items !== null) {
  55. let tempItems = [];
  56. Object.keys(items).forEach(key => {
  57. let obj = {};
  58. obj[key] = items[key];
  59. tempItems.push(obj);
  60. });
  61. items = tempItems;
  62. } else {
  63. items = [];
  64. }
  65. }
  66. _getAllOpts().forEach((opt) => {
  67. try {
  68. let found = items.some(it => {
  69. if (!it) return false;
  70. if (typeof(it) === 'string' && it === opt) {
  71. chrome.storage.local.set({[opt]: 'true'});
  72. return true;
  73. }
  74. else if (typeof(it) === 'object' && it !== null && it.hasOwnProperty(opt)) {
  75. chrome.storage.local.set({[opt]: it[opt]});
  76. return true;
  77. }
  78. return false;
  79. });
  80. if (!found) {
  81. chrome.storage.local.set({[opt]: 'false'});
  82. }
  83. } catch (e) {
  84. console.error('保存设置出错:', e, opt);
  85. // 出错时设置为默认值
  86. chrome.storage.local.set({
  87. [opt]: optionItemsWithDefaultValue[opt] === true ? 'true' : 'false'
  88. });
  89. }
  90. });
  91. callback && callback();
  92. };
  93. return {
  94. getAllOpts: _getAllOpts,
  95. getOptions: _getOptions,
  96. setOptions: _setOptions
  97. };
  98. })();