gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:55:30 25 4
gpt4 key购买 nike

我正在创建一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com