Domanda

Ho provato il seguente codice per ottenere un avviso alla chiusura della finestra del browser:

window.onbeforeunload = confirmExit;
function confirmExit() {
  return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?";
}

Funziona, ma se la pagina contiene un collegamento ipertestuale, facendo clic su quel collegamento ipertestuale viene generato lo stesso avviso. Devo mostrare l'avviso solo quando chiudo la finestra del browser e non facendo clic sui collegamenti ipertestuali.

È stato utile?

Soluzione

Mantieni il tuo codice così com'è e usa jQuery per gestire i collegamenti:

$(function () {
  $("a").click(function {
    window.onbeforeunload = null;
  });
});

Altri suggerimenti

Un'altra implementazione è la seguente che puoi trovare in questa pagina web: http://ujap.de/index.php/view/JavascriptCloseHook

<html>
  <head>
    <script type="text/javascript">
      var hook = true;
      window.onbeforeunload = function() {
        if (hook) {
          return "Did you save your stuff?"
        }
      }
      function unhook() {
        hook=false;
      }
    </script>
  </head>
  <body>
    <!-- this will ask for confirmation: -->
    <a href="http://google.com">external link</a>

    <!-- this will go without asking: -->
    <a href="anotherPage.html" onClick="unhook()">internal link, un-hooked</a>
  </body>
</html>

Quello che fa è usare una variabile come flag.

È possibile rilevare i clic sui collegamenti ipertestuali, ma non è possibile determinare se l'utente:

  • Tentativo di aggiornare la pagina.
  • Tentativo di chiudere la scheda del browser.
  • Tentativo di chiudere la finestra del browser.
  • Inserisci un altro URL nella barra degli URL e premi invio.

Tutte queste azioni generano l'evento beforeunload nella finestra , senza ulteriori informazioni precise sull'evento.

Per visualizzare la finestra di dialogo di conferma quando si eseguono le azioni precedenti e non visualizzarla quando si fa clic su un collegamento ipertestuale, attenersi alla seguente procedura:

  • Assegna beforeunload listener di eventi a finestra , che restituisce il testo di conferma come stringa, a meno che una specifica variabile (flag) sia impostata su < code> true .
  • Assegna clic all'evento document . Controlla se a è stato cliccato ( event.target.tagName ). Se sì, imposta flag su true .

Dovresti anche gestire i moduli inviati assegnando un listener di eventi submit a document .

Il tuo codice potrebbe apparire così:

let disableConfirmation = false;
window.addEventListener('beforeunload', event => {
  const confirmationText = 'Are you sure?';
  if (!disableConfirmation) {
    event.returnValue = confirmationText; // Gecko, Trident, Chrome 34+
    return confirmationText;              // Gecko, WebKit, Chrome <34
  } else {
    // Set flag back to false, just in case
    // user stops loading page after clicking a link.
    disableConfirmation = false;
  }
});
document.addEventListener('click', event => {
  if (event.target.tagName.toLowerCase() === 'a') {
    disableConfirmation = true;
  }
});
document.addEventListener('submit', event => {
  disableConfirmation = true;
});
<p><a href="https://stacksnippets.net/">google.com</a></p>
<form action="https://stacksnippets.net/"><button type="submit">Submit</button></form>
<p>Try clicking the link or the submit button. The confirmation dialog won't be displayed.</p>
<p>Try reloading the frame (right click -> "Reload frame" in Chrome). You will see a confirmation dialog.</p>

Nota che in alcuni browser devi usare event.returnValue nel listener prima del caricamento , e in altri usi l'istruzione return .

Vedi anche beforeunload documenti dell'evento .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top