Blame view

天文台pc/tianwentai-ui/node_modules/@mui/system/esm/cssVars/localStorageManager.js 1.12 KB
bc518174   王天杨   提交两个项目文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  function noop() {}
  const localStorageManager = ({
    key,
    storageWindow
  }) => {
    if (!storageWindow && typeof window !== 'undefined') {
      storageWindow = window;
    }
    return {
      get(defaultValue) {
        if (typeof window === 'undefined') {
          return undefined;
        }
        if (!storageWindow) {
          return defaultValue;
        }
        let value;
        try {
          value = storageWindow.localStorage.getItem(key);
        } catch {
          // Unsupported
        }
        return value || defaultValue;
      },
      set: value => {
        if (storageWindow) {
          try {
            storageWindow.localStorage.setItem(key, value);
          } catch {
            // Unsupported
          }
        }
      },
      subscribe: handler => {
        if (!storageWindow) {
          return noop;
        }
        const listener = event => {
          const value = event.newValue;
          if (event.key === key) {
            handler(value);
          }
        };
        storageWindow.addEventListener('storage', listener);
        return () => {
          storageWindow.removeEventListener('storage', listener);
        };
      }
    };
  };
  export default localStorageManager;