I have some pages on my site that allow users to create and edit posts. When a user is on these pages, I'd like to warn them before leaving the page. I can do that like this:
//Only warn if user is on a New or Edit page if(window.location.href.indexOf("/new") !== -1 || window.location.href.indexOf("/edit") !== -1 { window.addEventListener('beforeunload', function (e) { e.preventDefault(); e.returnValue = ''; }); //Doing this again because I don't know which version is compataible with all browsers window.onbeforeunload = function (e) { e.preventDefault(); e.returnValue = '' }; }; On a New or Edit page, the information in a form gets submitted to the server using JQuery ajax. The server returns a URL which the user gets redirected to to see the results of their post/update like this window.location.href = result; with result being the URL sent back from the server.
When that code runs to do the redirect, the user is getting the warning that they are about to leave the page they are on. I don't want it to do this on any redirects/navigation that the user has not performed. How could I stop/remove the warning in this instances?
UPDATE: This is not a duplicate. This question asks about preventing a beforeunloadevent happening on a redirect where the user has not requested to move away from the page himself.
beforeunloaddoesn't trigger unless the user initiates the navigation.beforeunloadevent registration without anyif/thenlogic and just with.addEventListener()instead of also with theonbeforeunloadproperty?