Intercept redirect page

Posted on

Question :

I have a page whose customer is selecting items, once selected I needed to check if the client will leave the current page because I need to alert him with a message like “Do you want to save your cart before leaving the page?” if yes save and continue the redirect, if not only redirects. I wanted to do to global redirects because I could pop up asking if it wanted and if after doing a window.location.href but I want it to serve everyone and not do the one by one the redirects … I got a javascript method which does an action before redirecting, but even showing a popup it redirects without expecting customer response. I want to know if it has how I intercept the redirect and after its response I let it redirect

The js function

 $(window).on("beforeunload", function(){
    console.log("Deixando a pagina");

but there in the form it does not wait for the answer and it already redirects


Answer :

Browsers tend increasingly to block such things.

If you try to use a confirm function in the beforeUnload event, to be more assertive for example, Chrome blocks the function call. I think other browsers will do the same.

If I’m not mistaken, I’ve seen people ask questions about how to circumvent such behavior, extensions, or the like. It would not surprise me if some ad blocker of life started messing with it.

For these reasons, I believe that stopping the more natural flow of user actions is not a good path. I would continue this research if-and-only-if this is a requirement on the grounds of law – I know that in Europe there are laws relating to how you can communicate with your users on your page.

However, if this is just a feature , my suggestion is to always save the cart in the browser’s local storage (and possibly the server as well) with every change in the cart. This gives the user a much more user-friendly experience, and you do not worry about interface streams and sub-flows, or trying to persuade the browser and its extensions about your code not to be malicious.


Leave a Reply

Your email address will not be published. Required fields are marked *