arpan
Using "beforeunload" with live redirects
Hello everyone,
I’m currently working on a page that features a live view, and I’m aiming to prevent users from accidentally leaving the page. To achieve this, I’m utilizing the beforeunload browser event in conjunction with a Phoenix hook. The structure of the hook is as follows:
export default function preventPageLeave() {
const beforeUnloadListener = (event) => {
// Prevent navigation and display a confirmation dialog
event.preventDefault();
event.returnValue = '';
};
return {
mounted() {
window.addEventListener("beforeunload", beforeUnloadListener, { capture: true });
}
};
}
This approach works seamlessly; however, I’m encountering a challenge when dealing with links on the page that use the link/1 function. For redirects managed by the Phoenix socket, which don’t necessitate a full page reload like navigation or patch operations, the beforeunload technique doesn’t prove effective.
Regrettably, I haven’t yet found an elegant solution to address this particular issue. I would greatly appreciate any insights or suggestions you might have.
Thank you in advance for your assistance!
First Post!
regex.sh
Maybe you could assign a class to link and then add event listener to all classes on the page?
Last Post!
arpan
This is the hook that I use right now
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;
}
)
}
};
}
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









