How do I execute something inside window.onbeforeunload = function (e) {..} in Chrome?

As mentioned in LapinLove404 in window.onbeforeunload not working in chrome , it seems that in Chrome inside a function, beforeunload

it is impossible to do anything else other than changing the confirmation message.

The following code works in FF and IE, but not Chrome:

<html>
<head>
<script type="text/javascript">
 window.onbeforeunload = function sair() {
  alert("This alert doesn't show up in Chrome");
  return "If you leave this page your data will be lost!";
 }
</script>
</head>
<body>
 <a href="http://www.example.com"> Leave the page </a>
</body>
</html>

      

How can I do something before the user leaves the page? For example, if I need to save the state of a page with an asynchronous call, or disable a previously set lock. I think there are many use cases for this, but unfortunately Chrome doesn't make it a trivial task. Any ideas for a workaround?

+3


source to share


2 answers


The functionality is onbeforeunload

very limited. I think the most you can do is return the message. You cannot prevent anyone from leaving the page. You cannot execute any code in onbeforeunload

. You can try onunload

for this.



+2


source


I believe you can set cookies, write to HTML5 storage, etc. But for security and denial of service, you cannot do certain things, like prompting the user, setting window.location, etc., things that might make it impossible for the user to navigate to the webpage they asked to go to.

This is generally not a good design choice to explicitly block on the server while a given user is on a web page and expects all paths from that page to allow you to remove that block. There are blocking methods that can be used to prevent most upgrade problems. One fairly simple way to do this is to make the client get the original data state and hang on to it. When they want to update the data, they re-submit both the original data and the new data. When the server acquires both old and new, it can issue a temporary lock, get the current data, and see if it matches the old data presented by the client. If so, then no one has changed the data during user editing. If old data and current data do not match,the data has been modified while editing by the user. If it was changed, then it depends on what to do - and the strategy could be anything from the last one to writing winnings, merging only the changed fields to deny the entry because the underlying data was changed and telling the user to look at the new state data and reapply any required changes.



There are other similar methods that include ID numbers or revision IDs instead of a copy of the old data.

+2


source







All Articles