Internet Explorer вызывает window.onbeforeunload на вызовы window.open и AJAX
Хорошо, я потратил некоторое время на эту проблему, и вот что я собрал:
-
Если вы делаете вызов AJAX в IE7, и у вас есть указанная функция window.onbeforeunload, он вызывает функцию onbeforeunload.
-
Если вы попытаетесь открыть новое окно с помощью window.open БЕЗ нарушения текущего окна, вызывается onbeforeunload.
Кто-нибудь знает, как остановить это? Я даже пытался установить переменную в значение ИСТИНА и проверить эту переменную в моей функции onbeforeunload, и она все еще работает дозатором! Мне просто нужно остановить выполнение этого метода для вызовов AJAX и новых вызовов окна.
Ответы
Ответ 1
Другой и, вероятно, более простой вариант - вернуть false при открытии всплывающего окна:
<a onclick="window.open(...); return false;" href="javascript:;" >my link</a>
Это, похоже, мешает IE думать, что вы покидаете страницу и запускаете событие. Все другие варианты не были особенно полезны для меня.
Ответ 2
Хорошо, у меня эта проблема. У меня есть (довольно грязная) работа для него.
В моем случае я хочу иногда блокировать навигацию, а не другие.
Итак, я устанавливаю флаг в окне, чтобы сообщить мне, хочу ли я заблокировать его. Итак, где вы делаете свой window.open, перед этим сделайте "window.allowExit = true", а затем в onbeforeunload, проверьте для window.allowExit = true.
У меня есть java script (SHowHelp), который вызывается из ссылки:
<a href="javascript:ShowHelp('argument')" >HERE</a>
onbeforeunload вызывается перед ShowHelp, поэтому я использовал onclick для установки флага
<a onclick="window.allowExit = true;" href="javascript:ShowHelp('argument')" >HERE</a>
Уродливый как грех, но, похоже, он работает!
Ответ 3
Это не решение, а объяснение для любого, кто заинтересован. Я только что проверил быстрый тест в IE 7, и он запускает событие onebeforeunload всякий раз, когда нажимается ссылка, если HREF не находится где-то на одной странице: например, если он не содержит #. Поэтому я предполагаю, что инженеры IE думали, что когда кто-то нажимает ссылку, которая не находится где-то еще на странице, они должны покинуть страницу, и в этом случае страница собирается выгрузить. Излишне говорить, что есть очевидные проблемы с этим мышлением.
Ответ 4
Я решил, что вам просто нужно отключить функцию window.onbeforeunload, прежде чем что-либо сделать, а затем вернуть ее, когда закончите.
Я только что отключил функцию в IE.
Ответ 5
У меня была та же проблема: в моем случае все запросы поступают из ajax-вызова, это упрощает решение, потому что когда я исправил значок со стандартной кнопкой, я сделал рекурсивную функцию, чтобы перенаправить все onclick на мою централизованную функцию, а затем разобрать rigth клик.
Я копирую решение для ajax-вызова, поддерживающего проблему href.
Это решение не позволяет вернуться на предыдущую страницу. Поместите код внутри файла с именем backbutton, js
Любой комментарий пишите на [email protected] с темой: javascript backbutton
<!-- backbutton developed by Manuel Parma 2011-06-10 -->
<!-- email: [email protected] -->
<!-- Add the next line into the <body> section as a first line -->
<!-- <script type="text/javascript" src="<path>/backbutton.js"></script> -->
<!-- Address used when backtoLogin is 1 or when there is not previous page from site -->
var returningAddress = "http://my returning address"
<!-- Message to display when an external action (back button, forward button, backspace) move without press the application buttons -->
var backButtonMessage = "Using the browser Back button may cause a loss in data. Please use the Back and Continue buttons at the bottom of the form."
<!-- 0=no / 1=yes (assume per default that the back button will be pressed -->
<!-- and come into action if this was NOT the case) -->
var backButtonPressed = 1;
<!--This var when is setted to 1 avoid to captureEvent set backbuttonPressed to 1, otherwise unload event cannot detect the right state of backButtonPressed-->
var onbeforeunloadeventFired = 0;
<!--Indicate to logic back to first page (login) when its value is 1 otherwise the logic back to previous page out of the site-->
var backtoLogin = 0;
var DoPostBackWithOptionsHook = null;
var DoPostBackHook = null;
<!-- Check the previous status -->
if (window.name == ""){
<!-- When window.name is empty, this is indicating the first call of site -->
window.name = "L0001";
}
else {
if (window.name == "L0000_back"){
<!-- In this condition the page is returning after a foward button press -->
setBackButton(0);
window.name = "";
<!-- the system reload the page to clean the data -->
window.location.href = returningAddress;
}
else {
if (window.name.indexOf("_back") > 4){
<!-- when the word back is present, the previous call is sending a message that the back button was pressed and the site is going out -->
<!-- get the internal counter -->
var sLastValue = modifynamevalue(0);
<!-- set the count to go back -->
var iCountBack = -(sLastValue * 1);
if (backtoLogin == 1) {iCountBack++;};
if (window.history.length - 2 < -iCountBack) {
iCountBack = -(window.history.length - 2);
}
<!-- the site is flag that first page needs to reload -->
window.name = "L0000_back";
setBackButton(0);
<!-- the site is returning to the first page or previous -->
window.history.go(iCountBack);
}
else {
<!-- increase the internal counter -->
var sLastValue = modifynamevalue(+1);
window.name = "L" + sLastValue;
}
}
}
<!-- Set the events needed to manage the back and forwar button situations -->
$(document).ready(function(){
if (typeof(Sys) == "object") {
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
window.onbeforeunload = onbeforeunloadEvent;
window.onunload = unloadEvent;
DoPostBackWithOptionsHook = WebForm_DoPostBackWithOptions;
WebForm_DoPostBackWithOptions = WebForm_DoPostBackWithOptionsHook;
doPostBackHook = __doPostBack;
__doPostBack = __doPostBackHook;
}
});
function WebForm_DoPostBackWithOptionsHook(options) {
setBackButton(0);
return DoPostBackWithOptionsHook(options)
}
function __doPostBackHook(eventTarget, eventArgument) {
if (backButtonPressed == 1) {
setBackButton(0);
}
return doPostBackHook(eventTarget, eventArgument)
}
function beginRequest(sender, args) {
setBackButton(0);
<!-- setting onbeforeunloadeventFired = 1 I take care to avoid anyone changed the Backbutton until endrequest -->
onbeforeunloadeventFired = 1;
}
function endRequest(sender, args) {
onbeforeunloadeventFired = 0;
setBackButton(1);
}
<!-- unload event handler -->
function unloadEvent(evt) {
<!-- double coundition using onbeforeunloadeventFired == 1 garantee avoid problemas with redirect operations -->
if ((backButtonPressed == 1) && (onbeforeunloadeventFired == 1)) {
<!-- decrement the internal counter -->
var sLastValue = modifynamevalue(-1);
window.name = "L" + sLastValue + "_back";
}
if (DoPostBackWithOptionsHook !== null) {
WebForm_DoPostBackWithOptions = DoPostBackWithOptionsHook;
};
if (doPostBackHook !== null) {
__doPostBack = doPostBackHook;
};
}
<!-- on before unload -->
function onbeforeunloadEvent(evt) {
onbeforeunloadeventFired = 1;
if (backButtonPressed == 1) {
return backButtonMessage;
};
}
<!-- used to set right backButtonPressed-->
function setBackButton(value){
if (value == 0) {
backButtonPressed = 0;
}
else {
if (onbeforeunloadeventFired == 0) {
backButtonPressed = 1;
}
}
}
<!-- increment and decrment the internal counter stored into windows.name -->
function modifynamevalue(iIncrement){
var iCount = (window.name.substring(1, 5) * 1) + iIncrement;
if (iCount < 0) {
iCount = 0;
}
var sNewValue = iCount.toString();
sNewValue = "0000".substring(0, 4 - sNewValue.length) + sNewValue;
return sNewValue;
}
Ответ 6
Sid_M сказал, что действительная точка, с этим дизайном браузера мы должны разработать наше приложение соответственно.
Зачем искать теги anchor и href для всплывающих окон, просто используйте метод onclick в метке или даже тег td и вызовите window.open
Простой пример из одного из моих приложений
<td class="popuplink" onMouseOver="this.style.cursor='hand'" onclick="javascript:openMe('img/howitworks.png', 'pndpopup', 600,650)"><u> How it works</u></td>
Ответ 7
Вы пытались удалить обработчик из события "onbeforeunload" перед вызовом window.open? Это может помочь, но я никогда не тестировал его.
Ответ 8
Это может очень помочь решить вашу проблему!
Потому что у меня была аналогичная проблема, и это сделало путь!
window.onbeforeunload = warnFunction;
var warnRequired = true;
function warnFunction () {
if (warnRequired) return ("Please Stay! Don't go!");
return ;
}
И всякий раз, когда я делаю вызов Ajax или всплывающее другое окно, я просто устанавливаю warnRequired равным false.
Еще одна вещь, которую нужно знать, когда вы вызываете вызов Ajax, что он синхронизирован, иначе переменная, возможно, еще не была установлена! (Отвратительный Gotcha!)