我有一个弹出窗口,如果我刷新它会丢失unbeforeunload回调。将unbeforeunload方法绑定到刷新的弹出窗口的正确方法是什么?
var url = ...,
title = ...,
params = [
"height=" + screen.height,
"width=" + screen.width,
"fullscreen=yes",
"resizable=yes",
"scrollbars=yes",
"toolbar=yes",
"menubar=yes",
"location=yes"
].join(",");
var popup = window.open(url, title, params),
onbeforeunloadCallback = function (e) {
var isRefresh = this.opener.title == undefined;
if (isRefresh) {
// It doesn't work for second refresh
// so what am I doing wrong ?
console.log("It is refreshing");
popup.onbeforeunload = onbeforeunloadCallback;
}
};
popup.onbeforeunload = onbeforeunloadCallback;
答案 0 :(得分:0)
最后,下面的代码解决了我的问题。请注意,下面的函数是ajax调用的成功,因此data.ParametersGuid
是从ajax返回的值。我也使用此值来区分多个弹出窗口,如下面的代码所示:
var url = ...,
title = ...,
params = [
"height=" + screen.height,
"width=" + screen.width,
"fullscreen=yes",
"resizable=yes",
"scrollbars=yes",
"toolbar=yes",
"menubar=yes",
"location=yes"
].join(",");
var isRefresh = false,
popup = window.open(options.url, options.title, params),
getCurrentPopup = function () {
var possibleCurrentPopupHandler = $.grep(window.popups, function (o) { return o.id === data.ParametersGuid }),
currentPopup = possibleCurrentPopupHandler.length > 0 ? possibleCurrentPopupHandler[0].popup : null;
return currentPopup;
},
setPopupCallbacks = function (p) {
p = p != null ? p : getCurrentPopup();
if (p == null) return;
console.log("setPopupCallbacks -----");
p.onload = onloadCallback;
p.onbeforeunload = onbeforeunloadCallback;
p.onunload = onunloadCallback;
p.onkeydown = onkeydownCallback;
},
onloadCallback = function (e) {
console.log("I'm in onloadCallback func");
setPopupCallbacks();
},
onbeforeunloadCallback = function (e) {
if (isRefresh) {
console.log("I'm refreshed in onbeforeunloadCallback func");
isRefresh = false;
setPopupCallbacks();
} else { // popup is being closed
console.log("I'm about to close in onbeforeunloadCallback func");
window.popups = $.grep(window.popups, function (o) { return o.id !== data.ParametersGuid });
element.clientModel.deleteSessionParameters(data.ParametersGuid);
}
},
onunloadCallback = function (e) {
console.log("I'm in onunloadCallback func");
setTimeout(function () { setPopupCallbacks(); }, 500);
},
onkeydownCallback = function (e) {
var ctrlRClick = e.keyCode == 65 && e.ctrlKey,
f5Click = (e.which || e.keyCode) == 116;
isRefresh = ctrlRClick || f5Click;
};
setPopupCallbacks(popup);
window.popups = window.popups || [];
window.popups.push({
id: data.ParametersGuid,
popup: popup
});