Is it possible to detect if a user has opened a new tab?

孤街醉人 提交于 2021-01-28 05:16:25

问题


We are developing a quiz platform where we want to detect if the user opens a new tab during the quiz. The user is not allowed to open a new tab and we want to track this to notify the teacher managing the quiz. We are targeting the major browsers (IE, Chrome, Firefox, Safari).

Is this possible? Thank you


回答1:


You can use the onblur event of the window object and write something like this:

function userCheated() {
    // The user cheated by leaving this window (e.g opening another window)
    // Do something
    alert("You can't cheat!");
}

window.onblur = userCheated;

NOTE: since that when the user goes away from your window you have no more control on the window, the userCheated function, due to slow execution, may be executed when the user comes back in your window, so sometimes the alert can show up when the user comes back. I think that it works fine too.

Browser support: since that some browsers may not be able to do this, I recommend you to use the jQuery plugin to make things work on more browsers, since that the jQuery API has a lot of compatibility adjustments.

With jQuery the code will be:

$(window).onblur(userCheated);



回答2:


You couldn't do this using javascript. It would have to be done with an extension for the browser I believe Internet explorer used to have an option for disabling tab browsing, have a look around the extensions for each browser you wish to do this on or look at making one. Would a better solution not be to restrict the websites you don't want them viewing rather than disabling the tab button?




回答3:


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
function userCheated() {
    // The user cheated by leaving this window (e.g opening another window)
    // Do something
    alert("New Tab Opened");
}

window.onblur = userCheated;

</script>`enter code here`
</head>`enter code here`
<body>
window.onblur = userCheated;
</body>
</html>


来源:https://stackoverflow.com/questions/25143698/is-it-possible-to-detect-if-a-user-has-opened-a-new-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!