0

I want to redirect users when they attempting to close or click back button. Is it possible to catch this kind of action with a script?

brasofilo
  • 23,940
  • 15
  • 86
  • 168
Suroj
  • 1
  • 1
  • Why? This is almost always a terrible user experience. If the user hits back, it shouldn't be prevented without a great reason (like going back would lose data they care about). – Mason11987 Apr 16 '18 at 16:48
  • @Mason, IMHO, the "why" is tangential, the meat of the matter is on the "how" :) – brasofilo Apr 17 '18 at 02:28
  • 1
    Of interest: [Good tutorial for using HTML5 History API (Pushstate?)](https://stackoverflow.com/q/4015613/1287812) – brasofilo Apr 17 '18 at 02:34

1 Answers1

1

What you're asking is essentially a browser security restriction. All you can really tell is if the user navigates away from the page (onbeforeunload, onunload fire) but you can't tell where they went unless you've set up your page to allow it.

HTML5 has introduced the HTML5 History API; in modern browsers that is, the onpopstate event will fire if the user navigates back to an earlier "page" on your site. Here's a great doc page regarding the history API.

Alternatively, there is a method which has been introduced in using some JavaScript. You can utilize location.hash and when the respective value changes by a user (for example by clicking back), redirect the user to whichever page you'd like.

brasofilo
  • 23,940
  • 15
  • 86
  • 168
CaliCo
  • 349
  • 1
  • 10
  • can you please guide me step by step for wordpress cms – Suroj Apr 17 '18 at 05:52
  • It's not as simple unfortunately; a handful of JavaScript will need to be implemented which works with the pushState function. You can then set your own event handler to redirect your users to the page you'd like them to. – CaliCo Apr 17 '18 at 15:34