@garage-panda/use-before-unload

0.1.0 • Public • Published

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

Package Sidebar

Install

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

Weekly Downloads

0

Version

0.1.0

License

MIT

Unpacked Size

5.63 kB

Total Files

5

Last publish

Collaborators

  • flushbg
  • mutafow
  • vpvladimirov