Question

I'm trying to ask the use if he really wants to leave the page where a youtube video is playing. But before asking the question "Are you sure to leave the page ?", I want to pause the video. I try with this code (instead of pause the video I just write something in a div), but the content of the div only changes after the user decided to stay on the page...Is there a way to fix it ?

    <script>
        var confirmOnLeave = function(msg) {
            window.onbeforeunload = function (e) {          

                e = e || window.event;
                msg = msg || '';
                document.getElementById('test').innerHTML = 'stop'; 
                // For IE and Firefox
                if (e) {e.returnValue = msg;}

                // For Chrome and Safari
                return msg;
            };

        };
        confirmOnLeave('Are you sure to leave the page ?');
    </script>
   <body>
    <div id='test'> a </div>
    </body>

jsfiddle : http://jsfiddle.net/Yrs47/

Thanks,

Was it helpful?

Solution

Nope -- "works as designed."

Back in the day, a lot of websites would abuse onbeforeunload to do things like -- reload the current page, open up a slew of pop-unders or just cancel the navigate away.

Now -- there is a semi-controllable action that you can do. Using Javascript, you can connect to every link on the page and open your dialogue box and ask what they'd like to do. That may catch some of your needs, but it wouldn't catch people opening a bookmark, clicking the back button or typing in a new URL.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top