javascript - 如何检查应用程序是否在 Reactjs 应用程序的另一个选项卡中打开

标签 javascript reactjs

我正在创建一个 React 应用程序,如果应用程序已经在另一个选项卡中打开,我希望用户无法在另一个选项卡中打开该应用程序。类似于 WhatsApp https://imgur.com/a/wugEAha .

有什么方法可以检测该应用是否已在另一个标签页中打开?

最佳答案

我正在回答我自己的问题,我已经成功地做到了这一点。我创建了一个自定义 React 钩子(Hook)来强制我的应用程序在单个选项卡上打开。

我会尽快改进我的代码,但就目前而言,这对我来说还不错。

参见示例:https://m407l.csb.app/

import { useState, useEffect, useRef } from "react";

const useIsMainWindow = () => {
  const initialized = useRef(false);
  const isNewWindowPromotedToMain = useRef(false);
  const windowId = useRef(null);
  const [isMain, setIsMain] = useState(true);

  const getWindowArray = () => {
    let storage = window.localStorage.getItem("checkTab");
    return storage ? JSON.parse(storage) : [];
  };

  const setWindowArray = (data) => {
    window.localStorage.setItem("checkTab", JSON.stringify(data));
  };

  const determineWindowState = () => {
    let windowArray = getWindowArray();

    if (initialized.current) {
      if (
        windowArray.length <= 1 ||
        (isNewWindowPromotedToMain.current
          ? windowArray[windowArray.length - 1]
          : windowArray[0]) === windowId.current
      ) {
        setIsMain(true);
      } else {
        setIsMain(false);
      }
    } else {
      if (windowArray.length === 0) {
        setIsMain(true);
      } else {
        setIsMain(false);
      }
      const newWindowArray = [...windowArray, windowId.current];
      setWindowArray(newWindowArray);
    }

    setTimeout(function () {
      determineWindowState();
    }, 1500);
  };

  const removeWindow = () => {
    var newWindowArray = getWindowArray();
    for (var i = 0, length = newWindowArray.length; i < length; i++) {
      if (newWindowArray[i] === windowId.current) {
        newWindowArray.splice(i, 1);
        break;
      }
    }
    setWindowArray(newWindowArray);
  };

  useEffect(() => {
    window.addEventListener("beforeunload", removeWindow);
    window.addEventListener("unload", removeWindow);
    isNewWindowPromotedToMain.current = true;
    windowId.current = Date.now().toString();
    determineWindowState();
    initialized.current = true;

    () => {
      window.removeEventListener("beforeunload", removeWindow);
      window.removeEventListener("unload", removeWindow);
    };
  }, []);

  return isMain;
};

export default useIsMainWindow;

关于javascript - 如何检查应用程序是否在 Reactjs 应用程序的另一个选项卡中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66210220/

相关文章:

javascript - ReactJS 中的路由。 URL已显示,但组件未呈现

javascript - react-table 在行单击上添加引用

javascript - 使用 node-sqlite3 将变量绑定(bind)到 SQL 语句

javascript - 带有 AJAX 问题的 jQuery 提交表单

c# - 调试javascript代码

javascript - 如何使用 Material ui 选项卡的 props 更改选项卡?

javascript - react : how to access base class from higher order components

javascript - react Hook : Why is it bad practice to pass the set state functions to a Child Component?

javascript - jquery:json请求输出

javascript - 不是 nvd3 或 d3 的默认 json 格式