How to stop refresh the page form the beforeunload event? - javascript

i'm using the 'beforeunload' event to detect the refresh event from the webpage.how to stop refresh the page from beforeunload event and i should not show alert message
window.addEventListener("beforeunload", this.onUnload);
onUnload = e => {
e.preventDefault();
// how to stop refresh the page from here and i should not show alert message.
//it is showing alert message. i no need to show the alert.
e.returnValue = "sure do you want to reload?";
}

It is not possible to prevent unloading a page without notifying the user.
Imagine you want to go to github.com at a time you are viewing stackoverflow.com - but it will simply prevent you from navigating away!
However, there was a time some browsers used to prevent unloading silently when you assign an empty string to the returnValue. But I believe that age of evil is gone now.

When i understand your following comment corectly, then you simply need to return zero, or false. So in your function you write:
onUnload = e => {
//e.preventDefault();
return false;
}
When i do this, i get an automated response from the Browser (for me its Chrome), if i really wanna close this website. And its in my language, so its i18n-compilant
It basically says "Are you sure you wanna refresh/close this website, data may get lost" and than 2 buttons with "Refresh/Close" and "Abort"

Related

Prevent user to leave page without the confirmation

I have found on StackOverflow this script that handles the issue when a user wants to leave the page, to ask him before doing it.
ISSUE
It is working fine (even though there is probably a much better solution) but I have realized that it is causing one "bug". When a user sends data from the form and the script asks him does he want to leave the page (because of the redirect) it still sends data. So, even if the user clicks on "Cancel" it will still proceed to the store() method and if the user adds something more and sends again the data I get duplicates. Is there a way to include "stop propagation" in this script?
CODE
window.onbeforeunload = function () {
return 'Are you sure you want to close this website?';
};
Additional question
Since this script is running with the Laravel Livewire, every time I click on any button related to the livewire (which won't redirect the user to the other page) script prompts the popup to ask if the user is sure he wants to leave the page. Is there any workaround (if you need some other code, write a comment because I am not sure which part could help you at all :) ) for this issue?
Try this:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}
// For Safari
return 'Sure?';
};
</script>
Here is a working jsFiddle

How can I warn user on back button click?

www.example.com/templates/create-template
I want to warn users if they leave create-template page. I mean whether they go to another page or to templates.
I use this code to warn users on a page reload and route changes should the form be dirty.
function preventPageReload() {
var warningMessage = 'Changes you made may not be saved';
if (ctrl.templateForm.$dirty && !confirm(warningMessage)) {
return false
}
}
$transitions.onStart({}, preventPageReload);
window.onbeforeunload = preventPageReload
It works as expected on a page reload and route changes if it is done by clicking on the menu or if you manually change it. However, when I click the back button, it does not fire the warning. only it does if I click the back button for the second time, reload the page, or change route manually.
I am using ui-router. When you click back button, you go from app.templates.create-template state to app.templates state.
How to warn if they press Back button?
First of all, you are using it wrong:
from https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload:
Note: To combat unwanted pop-ups, some browsers don't display prompts
created in beforeunload event handlers unless the page has been interacted
with; some don't display them at all. For a list of specific browsers, see the
Browser_compatibility section.
and
window.onbeforeunload = funcRef
funcRef is a reference to a function or a function expression.
The function should assign a string value to the returnValue property of the Event object and return the same string.
You cannot open any dialogs in onbeforeunload.
Because you don't need a confirm dialog with onbeforeunload. The browser will do that for you if the function returns a value other than null or undefined when you try to leave the page.
Now, as long as you are on the same page, onbeforeunload will not fire because technically you are still on the same page. In that case, you will need some function that fires before the state change where you can put your confirm dialog.
How you do that depends on the router that you are using. I am using ui-router in my current project and I have that check in the uiCanExit function.
Edit:
You can keep your preventPageReload for state changes in angular. But you need a different function for when the user enters a new address or tries to leave the page via link etc.
Example:
window.onbeforeunload = function(e) {
if (ctrl.templateForm.$dirty) {
// note that most broswer will not display this message, but a builtin one instead
var message = 'You have unsaved changes. Do you really want to leave the site?';
e.returnValue = message;
return message;
}
}
However, you can use this as below:(using $transitions)
$transitions.onBefore({}, function(transition) {
return confirm("Are you sure you want to leave this page?");
});
Use $transitions.onBefore insteadof $transitions.onStart.
Hope this may help you. I haven't tested the solutions. This one also can help you.

How Do I Use JavaScript To Prevent A Window From Closing Without The Popup With The "Are You Sure You Want To Leave This Page" Message?

I have a page for editing some data, and have some buttons for saving the data and closing the page. The page also has a modal popup for prompting the user if they want to exit without saving any changes they've made (if they have made any).
However, whilst this works when the user clicks on the buttons, this does not work if they click on the X at the top right corner of the window. I can get the page to stop when they click on this, and ask the usual "Are You Sure You Want To Leave This Page" message, but this isn't as nice as the modal popup, and I'd rather the user saw the same message regardless of which way they tried to exit the screen.
Can anyone explain how to prevent the window from closing if the user has made changes, but without using the "Are You Sure You Want To Leave This Page" message, so that I can show my nice modal version instead please?
You can't. If you could, it would get abused. So you can't. Your only option is the onbeforeunload handler, which will (with modern browsers) show a default message (no longer a custom message). That's it.
var showMessage = false; // set it to true when you want the message shown on exit
window.onbeforeunload = function(e) {
if (showMessage) {
var event = e || window.event;
var msg = "You have unsaved changes."; // Most modern browsers will no
// longer actually show this
// message, just their own.
// But to trigger it, you have to
// return one, so may as well make
// it useful.
if (event) {
event.returnValue = msg; // IE
}
return msg; // Everyone else
}
};

Confirm redirection from page in javascript

i am working on asp.net site that contains say three pages
page1.aspx
page2.aspx and page3.aspx
I want if user redirects from page1, alert box asking for confirmation should come. For this i have written following code
window.onbeforeunload = function () {
return 'Are you sure you want to leave?';
};
But this code run on every postback to server including pressing F5.
I want this code to run only when user redirects to any of remaining two pages
how can do this ??
try this code in javascript onload event in the pages only
if(confirm("Are you sure you want to leave?"))
{
//redirect to next page
return false
}
Handling in window.onbeforeunload may not be the straight forward way to do it since the alert message will be shown each and every time you load the page.
What you could do instead is call the confirmation js function in the from the DOM object that could possibly take the user to the different page.
For instance, let us suppose the below anchor tag takes the user to page two:
<a id="pageTwoAnchorTag" runat="server" href="~/Page2.aspx">Page 2</a>
you could add the below onclick event to get your confirmation when the user wants to go the page 2:
<a id="pageTwoAnchorTag" runat="server" onclick="return confirm('Are you sure you want to leave?')" href="~/Page2.aspx">Leave Records</a>
Only asking for confirmation in a couple of places might not be fully satisfying, since it will not trigger in all desired cases. For example, when you close the browser tab or window, your data will be lost.
I suggest to do the opposite: Register for the onbeforeunload as you already do, but include a "guard" which you disable on any action that should not trigger the confirmation (i.e. in postbacks):
window.shouldconfirm = true;
window.onbeforeunload = function () {
if (shouldconfirm) {
return 'Are you sure you want to leave?';
}
};
Register for the events that occur before a postback is executed (e.g. button click events, etc.) In those places, disable the confirmation:
window.shouldconfirm = false;
I am slightly surprised that the postbacks trigger the onbeforeunload event. I though to remember that on form posting the event is not triggered, and that a ASP.NET postback is implemented as a form post action.

JavaScript interrupt event

Here is the situation :
If I am in page-1 now I am clicking a link from page-1 to navigate to page-2. Before page-2 is loaded I am hitting escape so that still I am staying in page-1.
At that point I want to track that event.
Is there any JavaScript event so that I can track the above scenario?
More Info :
To avoid concurrent request to the "page-2", when the user clicks a link from page-1 I am redirecting to page-2 and disabling the link (to avoid multiple request to "page-2). At this point when we hit Esc and abort loading page-2, I need to enable the link again in page-1.
I tried using this code:
<html>
<head>
<script>
document.onkeypress = KeyPressed;
function KeyPressed(e)
{
if (!e) e = window.event; //IE Compatibility
alert(e.keyCode);
}
</script>
</head>
<body>
Stack Overflow
</body>
</html>
It detects any key pressed while you're on the page. Once you click on the SO link and hit escape, nothing happens. The browser is already receiving a response from the SO server and is starting to process it, this page has already been "left", despite appearances when you see "Waiting for http://stackoverflow.com" in your browser's status bar.
Your idea of handling this event is plain wrong. Blocking the button is required to make the user unable to do double post data. However, the request is sent instantaneously(!) after the click on the link.
So, if you click the link once, stop the page, then click second time - it will submit it twice, and that is not what is intended to happen.
Two events are triggered when the page unloads.
window.onUnload
window.onBeforeUnload
You can use these events to cancel the unload of the page, however after that, there page is considered done.
What you can do is make the page wait 5 secs or so before going to the new page:
eg:
window.onunload = (function() {
var time = new Date();
var cancel = false;
window.onkeypress = function (e) {
if ((e || window.event).keyCode == 27) cancel = true;
};
while(time > new Date() - 5000) {
if (cancel) return false;
}
});
In fact that may cause some browsers to hang since you're taking up all process time given to the JS script. ie: in the while block.
You could probably avoid that by doing a blocking function call, that isn't so process intensive, like one that is bound by network latency. eg: XMLHttpRequest() etc. I don't think calls that are queued such as setTimeout() will work here, as they don't block.
Since the <a href> tag tells the browser to move to another page, it's up to it to decide if it will still have your script running. If I were it, I wouldn't listen.
If you want to override that, I guess you should tell the browser not to listen to that particular onClick event, and put a callback in place that loads the target page in the background. This assures your page is still active. After the target page has loaded (by your script), you could kindly ask the browser to update itself with the received content.
So that's the theory. I have no idea if the DOM lets you just override the content of a loaded page, but I guess it does.

Categories

Resources