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");
}
}
});