移动标签页切换监听什么事件

问题描述 投票:0回答:1

我目前有这段反应代码来监听调用

reconnectedCallback

import { useEffect, useState } from "react";
import usePrevious from "../usePrevious";

  const useTabVisible = (reconnectedCallback: () => void) => {
    const [visible, setVisible] = useState<boolean>();
    const prevVisible = usePrevious(visible);

    useEffect(() => {
      const handleVisibilityChange = () => {
        setVisible(document.visibilityState === "visible");
      };

      window.addEventListener("visibilitychange", handleVisibilityChange);
      return () => {
        window.removeEventListener("visibilitychange", handleVisibilityChange);
      };
    }, []);

    useEffect(() => {
      if (prevVisible === false && visible) {
        reconnectedCallback();
      }
    }, [prevVisible, reconnectedCallback, visible]);
  };

  export default useTabVisible;

这部分代码

 window.addEventListener("visibilitychange", handleVisibilityChange);
监听可见性变化。因此,当我切换到 google chrome 的另一个选项卡并返回到我的应用程序的选项卡时,会调用
reconnectedCallback

但是,我也希望该应用程序适合移动设备,因此,如果我在网站上使用 iPhone 进行 Safari 浏览,我会将其留在网站上一段时间,然后切换到其他应用程序,例如 Subway Surfer 或 Whatsapp 或我的手机主屏幕,当我切换回来时,我想调用reconnectedCallback,但是这个visibilitychange没有被触发。

什么事件会监听移动设备的应用程序间切换,尤其是在 safari 时?我尝试了

focus
blur
但它们都不起作用。当一个网站已经过时一段时间了,这个术语又叫什么?

javascript reactjs mobile addeventlistener event-listener
1个回答
0
投票

您可以使用事件侦听器

pagehide
pageshow
(针对移动设备)和
visibilitychange
(针对桌面设备)。

import { useEffect, useState } from "react";
import usePrevious from "../usePrevious";

const useTabVisible = (reconnectedCallback: () => void) => {
  const [visible, setVisible] = useState<boolean>();
  const prevVisible = usePrevious(visible);

  useEffect(() => {
    const handleVisibilityChange = () => {
      setVisible(document.visibilityState === "visible");
    };

    const handlePageShow = () => {
      setVisible(true);
    };

    const handlePageHide = () => {
      setVisible(false);
    };

    window.addEventListener("visibilitychange", handleVisibilityChange);
    window.addEventListener("pageshow", handlePageShow);
    window.addEventListener("pagehide", handlePageHide);

    return () => {
      window.removeEventListener("visibilitychange", handleVisibilityChange);
      window.removeEventListener("pageshow", handlePageShow);
      window.removeEventListener("pagehide", handlePageHide);
    };
  }, []);

  useEffect(() => {
    if (prevVisible === false && visible) {
      reconnectedCallback();
    }
  }, [prevVisible, reconnectedCallback, visible]);
};

export default useTabVisible;
© www.soinside.com 2019 - 2024. All rights reserved.