2021-05-13

同源 tab 页之间的通信 localStorage 实现

// localUserListener.ts
function noop() {}

export class LocalListener {
  key: string;

  constructor(key) {
    this.key = key;
    // 回调只有在 set 不同值时才触发
    window.addEventListener("storage", (e: StorageEvent) => {
      if (e.key === key) {
        this.handleStorage();
      }
    });
  }

  setItem(val) {
    window.localStorage.setItem(this.key, JSON.stringify(val));
  }

  handleStorage() {}

  clearListener() {
    window.removeEventListener("storage", this.handleStorage);
  }
}

type Params = {
  storageKey: string,
  changeCallback: () => void,
}

export default function userChangeFresh(
  opt: Params = { storageKey: "", changeCallback: noop },
) {
  const listener = new LocalListener(opt.storageKey);
  listener.handleStorage = opt.changeCallback;

  function onReducer(reducer) {
    return (state, action) => {
      const newState = reducer(state, action);
      if (action.type === "user/fetchCurrent/@@end") {
        const userInfo = newState.user.currentUser;
        listener.setItem(userInfo.loginName);
      }
      return { ...newState };
    };
  }

  return {
    onReducer,
  };
}

在 global.ts 中引入:

import userChangeFresh from "./localUserListener";

使用:

const opt = {
      storageKey: "test",
      changeCallback: () => {
        window.location.reload();
      },
    };
app.use(userChangeFresh(opt));

你可能感兴趣的:(2021-05-13)