javascriptreactjsreloadautoplayreact-player

Distinguishing between page reloads and redirects for video autoplay in React


Problem:

I'm working on a React application where I have implemented video autoplay functionality using the react-player library. The videos autoplay correctly when the page redirects (e.g., from localhost:5173/ to localhost:5173/home), as there is user interaction involved. However, I'm facing issues when the page reloads (e.g., from localhost:5173/home to localhost:5173/home).

Videos autoplay on page redirects but not on page reloads. I prefer not to mute the video for autoplay to work due to user experience considerations.

Question:

How can I reliably distinguish between a page reload and a page redirect in my React application? Is there a way to handle video autoplay on page reloads without muting the video?

Code:

const VideoPlayer = ({ url, cb, videopause, setVideoPause, index }) => {
  const [isPlaying, setIsPlaying] = useState(false);

  const handlePlay = () => {
    setIsPlaying(true);
  };

  useEffect(() => {
    if (![-1].includes(index)) {
      setIsPlaying(true);
      setVideoPause(false);
    }
  }, [index, setVideoPause]);

  return (
    <>
      <div
        className={`${videopause
          ? "h-[15vh] md:h-[25vh]"
          : "h-[50vh] md:h-[60vh] md:min-w-fit"
          } rounded-lg relative flex`}
      >
        <ReactPlayer
          className="react-player"
          url={url}
          playsinline={true}
          autoPlay={true}
          width="100%"
          height="100%"
          controls={false}
          playing={isPlaying && !videopause}
          onEnded={cb}
        />
        {!isPlaying && (
          <button
            onClick={handlePlay}
            className="absolute w-20 h-20 text-white bg-black bg-opacity-50 rounded-full"
            style={{
              top: "50%",
              left: "50%",
              transform: "translate(-50%, -50%)",
            }}
          >
            Play
          </button>
        )}
        {videopause && (
          <>
            <div className="absolute top-0 left-0 w-full h-full bg-black opacity-30 rounded-3xl"></div>
            <img
              src={replay_icon}
              alt="Replay"
              className="absolute w-8"
              style={{
                top: "50%",
                left: "50%",
                transform: "translate(-50%, -50%)",
              }}
              onClick={() => {
                setVideoPause(false);
                setIsPlaying(true);
              }}
            />
          </>
        )}
      </div>
    </>
  );
};

export default VideoPlayer;

I tried using flags to track video playback status, but they show the video as playing even when paused. Also, i have tried this :

const navigationType = performance.navigation.type;
    if (navigationType === 1) {
      console.log("Page is being reloaded");
      // Reset playback state as needed on reload
      setIsPlaying(false); // Example: reset to false on reload
      localStorage.removeItem("videoPlaybackState"); // Clear stored state on reload
    }
  }, []);

but it works even when the page is redirected. Any insights or suggestions would be greatly appreciated.


Solution

  • I would suggest you use performance.navigation API with more specific handling for both cases.

    Since performance.navigate.type returns a value that represents how the page was navigated, you can leverage on it to differentiate between reloads and other navigations e.g 0 for TYPE_NAVIGATE 1 for TYPE_RELOAD 2 for TYPE_BACK_FORWARD 255 for TYPE_RESERVED

    check MDN Web Docs: Performance API

    And also use local storage to persist a flag or a state indicating whether the page has been reloaded