ventana pestaña navegador evitar evento cerrar capturar automaticamente antes alerta abrir javascript asp.net session

javascript - evitar - ¿Cómo detectar el evento de cerrar la ventana/pestaña del navegador?



evitar cerrar ventana javascript (6)

¡Sí hay! Después de mucho dolor de cabeza encontré una solución a esto.

Monitor.php

Este archivo php estará monitoreando el evento de cierre del navegador. Una vez que se cierra el navegador, connection_aborted devolverá 1, por lo que el bucle se interrumpirá.

<?php // Ignore user aborts and allow the script // to run forever ignore_user_abort(true); set_time_limit(0); echo connection_aborted(); while(1) { echo "Whatever you echo here wont be printed anywhere but it is required in order to work."; flush(); if(connection_aborted()) { break; // Breaks only when browser is closed } } /* Action you want to take after browser is closed. Write your code here */ ?>

Caller.php

Este es el archivo que llamará Monitor.php

<?php Header(''Location: monitor.php''); ?>

Parent.html

Este será el archivo con el que realmente interactuarás. Al cargar esto, se realizará directamente una llamada AJAX a Caller.php que iniciará automáticamente Monitor.php en modo de fondo.

<script> var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { } } xmlhttp.open("GET", "Caller.php", true); xmlhttp.send(); </script>

Así que el flujo final es Parent.html -----> Caller.php -----> Monitor.php

Estoy probando con una función antes de descargar y descargar. Pero no funcionó. Al hacer clic en un enlace o actualizar, este evento se activó. Quiero un evento que se activa solo cuando se cierra una ventana o pestaña del navegador. El código debe funcionar en todos los navegadores.

Estoy usando el siguiente código en Masterpage.

<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>

y en mi etiqueta de cuerpo:

El código anterior funciona en IE pero no en Chrome ...


Este código evita los eventos de la casilla de verificación. Funciona cuando el usuario hace clic en el botón de cierre del navegador, pero no funciona cuando se hace clic en la casilla de verificación. Puede modificarlo para otros controles (cuadro de texto, botón de radio, etc.)

window.onbeforeunload = function () { return "Are you sure?"; } $(function () { $(''input[type="checkbox"]'').click(function () { window.onbeforeunload = function () { }; }); });


No puedes detectarlo con javascript.

Solo los eventos que detectan la descarga / cierre de páginas son window.onbeforeunload y window.unload . Ninguno de estos eventos puede indicarle la forma en que cerró la página.


También puedes hacer como a continuación.

poner debajo del código de script en la etiqueta del encabezado

<script type="text/javascript" language="text/javascript"> function handleBrowserCloseButton(event) { if (($(window).width() - window.event.clientX) < 35 && window.event.clientY < 0) { //Call method by Ajax call alert(''Browser close button clicked''); } } </script>

Llame a la función anterior de la etiqueta del cuerpo como abajo

<body onbeforeunload="handleBrowserCloseButton(event);">

Gracias


para hacer la diferencia entre una actualización y una pestaña o navegador cerrado, aquí está cómo lo arreglé:

<script> function endSession() { // Browser or Broswer tab is closed // Write code here } </script> <body onpagehide="endSession();"> </body>


<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>

Respondí en ¿Puede usar JavaScript para detectar si un usuario ha cerrado una pestaña del navegador? cerrar un navegador? ¿O ha dejado un navegador?