settings.js 3.2 KB

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