I want a simple redirect to a location when a user clicks the "Back Button" in the Browser.
The problem is, I only want this when he is leaving the page to a different site where he comes from. So find out bounces from the site to redirect them.
That was my try: But it didn’t work :
function bounce_redirect() {
if ('' === window.top.location.hash && '#' !== window.location.href.slice(-1)) {
location.replace('/faq');
}
}
window.addEventListener("popstate", bounce_redirect);
Does someone have an idea how to get that run? It is a school project and not for a live running page as I know, that is not a good way to hold people.
2
Answers
Redirecting a user to a different page when they press the back button can be achieved using JavaScript. However, it’s important to note that this behavior is often considered intrusive and can be disruptive to the user’s browsing experience. Users typically expect the back button to navigate within their browsing history, and forcing a redirect can be frustrating.
Please be aware that many users find forced redirects like this frustrating and it can create a poor user experience. It’s generally recommended to use this sparingly and only for specific, well-justified cases, such as when you have a legitimate need to prevent users from going back to a certain page (e.g., to protect data entry or ensure a specific workflow).
as you mention that is not a good way to hold people. and I think isn’t any way to do that without any bugs. i mean without ditching way,
but I think you can do it by "addEventListener beforeunload"
and check " window.location.href " is contains what you want or not
if it isn’t change it to your URL
something like :