# Using "beforeunload" with live redirects

**URL:** <https://forum.elixirforum.com/t/using-beforeunload-with-live-redirects/57504>\
**Category:** Questions\
**Tags:** phoenix, liveview\
**Created:** [August 8, 2023, 11:33am UTC](https://forum.elixirforum.com/t/using-beforeunload-with-live-redirects/57504 "2023-08-08T11:33:01Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![arpan](https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/arpan/32/17601_2.png) [@arpan](https://forum.elixirforum.com/u/arpan)\
**Post date:** [October 1, 2024, 7:18pm UTC](https://forum.elixirforum.com/t/using-beforeunload-with-live-redirects/57504/6 "2024-10-01T19:18:05Z")

</div>

This is the hook that I use right now

```elixir
export default function prevent_page_leave() {
  const beforeUnloadListener = (event) => {
    // Prevent navigation and show confirmation dialog
    event.preventDefault();
    return event.returnValue = '';
  };

  return {
    mounted() {
      window.addEventListener("beforeunload", beforeUnloadListener, { capture: true });

      // Remove "beforeunload" event listener and redirect to given path
      addEventListener(
        "phx:force_redirect",
        e => {
          window.removeEventListener("beforeunload", beforeUnloadListener, { capture: true });
          window.location.href = e.detail.to;
        }
      )
    }
  };
}

```

---

_[View the full topic](https://forum.elixirforum.com/t/using-beforeunload-with-live-redirects/57504)._
