In jQuery, display alerts when the user tries to switch tabs or switch windows

advertisements

I want to make an exam page, and not let the user visiting other pages until he submits it.

It seems like onunload and onbeforeunload are for cases where the user explicitly close the page. I was wondering if there is a trigger for the event when the page lose focus.


You can use the $(window).blur() event for that.

$(window).blur(function() {
    console.log("page left");
});

Or even better the page visibility check which you can find here: https://developer.mozilla.org/en-US/docs/Web/Guide/User_experience/Using_the_Page_Visibility_API

However, even when you show an alert, you won't be able to keep someone on your page. They can just checkbox the alert to not show again. What you could do is to notify them that the test will auto submit if they leave the tab which they probably won't want.

$(window).blur(function() {
    if(!confirm("Notice about leaving the page")) {
        if(!document.hasFocus()) {
            console.log("user left the page");
        }
    }
});