我正在尝试使用onbeforeunload和Unload函数。但它并没有起作用。单击链接或刷新时,会触发此事件。我想要一个仅在浏览器窗口或选项卡关闭时触发的事件。代码必须在所有浏览器中都能工作。
我在母版页中使用了以下代码。
<script type="text/jscript">
var leaving = true;
var isClose = false;
function EndChatSession() {
var request = GetRequest();
request.open("GET", "../Chat.aspx", true);
request.send();
}
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event)
keycode = window.event.keyCode;
else if (e)
keycode = e.which;
if (keycode == 116) {
isClose = true;
}
}
function somefunction() {
isClose = true;
}
window.onbeforeunload = function (e) {
if (!e) e = event;
if (leaving) {
EndChatSession();
e.returnValue = "Are You Sure";
}
}
function GetRequest() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
在我的body标签中:
上面的代码可以在IE中运行,但不能在chrome中运行。
发布于 2014-05-21 05:07:39
此代码阻止checkbox事件。当用户单击浏览器关闭按钮时,它会工作,但当复选框单击时,它不会工作。您可以为其他控件(文本框、单选按钮等)修改它。
window.onbeforeunload = function () {
return "Are you sure?";
}
$(function () {
$('input[type="checkbox"]').click(function () {
window.onbeforeunload = function () { };
});
});
发布于 2014-03-06 16:30:01
你不能用javascript检测到它。
只有window.onbeforeunload和window.unload这两个事件能够检测到页面卸载/关闭。这两个事件都不能告诉您关闭页面的方式。
发布于 2015-03-30 15:50:11
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
var validNavigation = false;
function wireUpEvents() {
var dont_confirm_leave = 0; //set dont_confirm_leave to 1 when you want the user to be able to leave withou confirmation
var leave_message = 'ServerThemes.Net Recommend BEST WEB HOSTING at new tab window. Good things will come to you'
function goodbye(e) {
if (!validNavigation) {
window.open("http://serverthemes.net/best-web-hosting-services","_blank");
return leave_message;
}
}
window.onbeforeunload=goodbye;
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
</script>
https://stackoverflow.com/questions/21227383
复制相似问题