Window.onbeforeunload detects if POST or GET

Is there a way in the window.onbeforeunload event to determine if the new POST request (on the same page) or GET (go to page)? It would also be great to see a new .location document.

window.onbeforeunload = winClose;
function winClose() {
    //Need a way to detect if it is a POST or GET
    if (needToConfirm) {       
        return "You have made changes. Are you sure you want?";
    }
}
+3
source share
2 answers

Here is how I did it:

$(document).ready(function(){
  var action_is_post = false;
  $("form").submit(function () {
    action_is_post = true;
  });

  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    if (!action_is_post)
      return 'You are trying to leave this page without saving the data back to the server.';
  }
});
+12
source

It looks like you need to attach to a form or to certain links. If the event is triggered by a link, and there is a query string full of variables, it will act as a GET. If this is a form, you will need to check the METHOD and then provide the URL based on the data provided in the form itself.

<a href="thisPage.php">No method</a>
<a href="thisPage.php?usrName=jonathan">GET method</a>
<form method="GET" action="thisPage.php">
  <!-- This is a GET, according to the method -->
  <input type="text" name="usrName" value="jonathan" />
</form>
<form method="POST" action="thisPage.php">
  <!-- This is a POST, according to the method -->
  <input type="text" name="usrName" value="jonathan" />
</form>

, , .

/* Check method of form */
$("form").submit(function(){
  var method = $(this).attr("method");
  alert(method);
});

/* Check method of links...UNTESTED */
$("a.checkMethod").click(function(){
  var isGet = $(this).attr("href").get(0).indexOf("?");
  alert(isGet);
});
0

Source: https://habr.com/ru/post/1703262/


All Articles