utils.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * 工具类
  3. */
  4. class Utils {
  5. /**
  6. * 防抖函数
  7. * @param {Function} func 要执行的函数
  8. * @param {number} wait 等待时间
  9. * @returns {Function}
  10. */
  11. static debounce(func, wait) {
  12. let timeout;
  13. return function executedFunction(...args) {
  14. const later = () => {
  15. clearTimeout(timeout);
  16. func(...args);
  17. };
  18. clearTimeout(timeout);
  19. timeout = setTimeout(later, wait);
  20. };
  21. }
  22. /**
  23. * 安全地获取存储数据
  24. * @param {string} key
  25. * @returns {Promise}
  26. */
  27. static async getStorageData(key) {
  28. try {
  29. const result = await new Promise((resolve) => {
  30. chrome.storage.local.get(key, (data) => {
  31. if (chrome.runtime.lastError) {
  32. console.warn("Storage access error:", chrome.runtime.lastError);
  33. resolve(null);
  34. return;
  35. }
  36. resolve(data[key]);
  37. });
  38. });
  39. return result;
  40. } catch (error) {
  41. console.warn("Storage access error:", error);
  42. return null;
  43. }
  44. }
  45. /**
  46. * 安全地设置存储数据
  47. * @param {string} key
  48. * @param {any} value
  49. * @returns {Promise}
  50. */
  51. static async setStorageData(key, value) {
  52. try {
  53. await new Promise((resolve) => {
  54. chrome.storage.local.set({ [key]: value }, () => {
  55. if (chrome.runtime.lastError) {
  56. console.warn("Storage access error:", chrome.runtime.lastError);
  57. resolve();
  58. return;
  59. }
  60. resolve();
  61. });
  62. });
  63. } catch (error) {
  64. console.warn("Storage access error:", error);
  65. }
  66. }
  67. }