Search code examples
javascriptonbeforeunloadeventtrigger

Javascript, do something before leaving page


Because of the new GDPR law, when a user keep navigating on our website, that will means that he agreed to the cookies, and we need to record that.

So, I need to be able to do something before an user leave a page, following a link or validating a form. How can I do that ?

I tried using window.onbeforeunload, but this trigger a alert, asking the user if he really want to leave the website. I would have to do two action before leaving a page:

  • Recoring the cookies
  • Launch a trigger that is going to set the trackers

        window.onbeforeunload = function (e) {
            // Record the cookie
            // Launch a trigger to add the trackers
            return true;
        };
    

Maybe I'm making a mistake, if anyone could give me a hand


Solution

  • From the documentation:

    When this event returns (or sets the returnValue property to) a value other than null or undefined, the user is prompted to confirm the page unload.

    https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

    So you should not do a return true; at the end of this function.