Open Lightbox Popup on Browser Close

  • drugistry
    Asked on November 14, 2018 at 11:48 PM

    Dear Team,
    How do I open lightbox popup on Browser close, ie., when our visitors are leaving the website. This will enable me to show some offers when they leave our website.


    Thank you

  • Adrian
    Replied on November 15, 2018 at 6:31 AM

    You can achieve this by adding the following JavaScript code on the page where the lightbox is embedded.

            <script>
                function openLightBox() {
                    var btn = document.querySelector("a.btn");
                    btn.click();
                }
                window.addEventListener('beforeunload', function (e) {
                    e.preventDefault();
                    openLightBox();
                    e.returnValue = 'Are you sure you want to leave?';
                });
            </script>

    DEMO: https://shots.jotform.com/adrian/embed/lightshot/83182387594974.html

    Please note that for this code to work:

    - the user must click at least once somewhere on the page
    - the form has to be embedded using the lightbox method

    As you can see in the demo, a default browser alert will appear where the user can choose if they want to leave the page or stay on the page. If they choose to stay on the page, the lightbox form will pop up.