Skip to content

garage-panda/use-before-unload

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

npm version

use-before-unload

About

A React hook that uses the onbeforeunload (beforeunload) event and tracks when the user has been Refreshed or Canceled the default browser message. It is impossible to track if the user has left the page and is not a good idea to execute code after that.

Install

npm i @garage-panda/use-before-unload

Usage

import React from "react";
import { useBeforeUnload } from "@garage-panda/use-before-unload";

function App() {
  const setEnabledBeforeUnload = useBeforeUnload({
    initEnable: false, // do you need to be enabled by default
    onRefresh: () => {
      // the page has been refreshed (the user has clicked Reload)
    },
    onCancel: () => {
      // the user has clicked Cancel
    }
  });

  React.useEffect(() => {
    setEnabledBeforeUnload(true); // you can dynamically enable or disable the beforeunload event

    if (!sessionStorage.length) {
      // the only way to know that the user has land on your site (and has not refreshed the page)
    }
  }, []);
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Support

If you like what you see, feel free to support us!

License

MIT

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published