I know this is not recommended, but I need it because I have an iframe inside the page who has the actual content and I want that when the users hits refresh button, iframe reloads not entire page.
I know I have to call onunload / onbeforeunload event, but I don't want to ask me if I want to leave the window, just don't.
Is that possible? I've got handled the F5 key, but I like to prevent refreshing from button too.
UPDATE: I wrote this 5 years ago, browsers do different stuff now, you can still use this for testing your browser set, but your experience may vary from my old research.
Experimenting using jQuery, because I'm lazy.
Theoretically, preventing the default behavior should stop the event from doing whatever it is supposed to do. It doesn't work with the events in my example and has different results in different browsers. I put the Math.random() in to determine if the page has been reloaded or not. Because different browsers do different things, I highly recommend NOT using this in a production environment.
<body>
<p></p>
<script type="text/javascript">
$('p').append(Math.random());
$(window).bind({
beforeunload: function(ev) {
ev.preventDefault();
},
unload: function(ev) {
ev.preventDefault();
}
});
</script>
</body>
Using CTRL-R or F5 or Reload Button:
Safari: Does nothing
Chrome: Does nothing
Opera 10 & 11: Does nothing
Firefox 7.x: Shows a special prompt with two buttons:
Stay on Page - Does not reload page
Leave Page - Reloads the page
IE7 & IE8: Shows a prompt with two buttons:
OK - Reloads the page
Cancel - Does not reload the page
IE9: Shows a prompt with two buttons:
Leave this page - reloads
Stay on this page - does not reload
Firefox Prompt (you can tell I tested it on a Mac)
IE7 & IE8 Prompt
IE9 Prompt
In closing:
Yes, I did not test IE6, I deleted my VM which had it installed, I don't have a VM with IE10 beta installed, so you're out of luck on that too.
You might also experiment with cancelBubble and stopPropagation or maybe return false; might reveal something useful. I'm down with Jordan's reply that you shouldn't be trying to override the defaults, so I'm concluding my experiment here.
Returning false in an onsubmit event prevents the form from being submitted and stays in the same page without any user interaction..
For example..
when a form having input field is empty and submitted this javascript check for validation and returns accordingly..
If false is returned nothing is done(i.e. page is not refreshed or redirected)..
If the validation is ok and if true is returned the form action is performed..
function validateForm(Str) {
mystring=document.getElementById('inputid').value;
if(!mystring.match(/\S/)){
alert ('Please Enter a String.Field cannot be empty');
return false;
}else{
return true;
}
}
Related
Does anyone know a way, via JavaScript, that I can either clear Safari's bfcache, or force it to reload rather that used a cached version of a page?
I have a web application that is running tests, and there is JavaScript which monitors a countdown (a timeout):
timeoutId = window.setInterval(function () {
timeoutRemaining--;
if (timeoutRemaining <= 0) {
location.href = myTimeoutLocation;
}
}, timeoutInterval);
This all works fine until I get to myTimeoutLocation. The behavior is that, if a user clicks the back button, the test should continue. However, when navigating back, I find that IE and Chrome reload the page, but Firefox and Safari are showing the cached page. I need to make sure that a cached page is NEVER shown. I can fix this problem in Firefox by adding:
window.onunload = function () { };
to my script, but that hasn't worked in Safari since Safari 5.x (as far as I can tell). I found another solution:
window.addEventListener("pageshow", function(evt){
if(evt.persisted){
setTimeout(function(){
window.location.reload();
},10);
}
}, false);
This worked to an extent... The problem I have now is that even with the above code, I am receiving a dialog box: ... which I'm apparently not allowed to embed. The dialog says that in order to display the page, information must be sent to the server, with the appropriate confirm or deny buttons. I did try setting forceGet to true, but that did not solve the problem with the dialog appearing. I should mention that clicking Resend has the desired effect.
Non-embedded image of dialog
And yes, I realize the image is of Firefox, not Safari.
In case it makes any difference (even though this is a JavaScript question), the site is coded in .NET/MVC4 and is hosted in IIS.
Thank you in advance for any help/thoughts/information/pointers in the right direction.
Below is my code to detect and stop the browser's back button in iPad browsers.
$(window).bind("pagehide", function(e) {
})
How can I stop the page going back on browsers' back button click in iPad browsers?
You can use the onbeforeunload event that triggers when a user is leaving your page, whether it's by hitting the back button, entering a new URL or closing the browser.
Here is an example:
window.onbeforeunload = function(){
return 'You are leaving!?';
}
And here is the result on Chrome:
This event seems to be inconsistent across browsers as some will not support it, some will execute whatever function you pass it, and some will reject the function if it doesn't return a string to put in the confirmation box.
As commenter Alex Wayne stated, think twice about this. It can really create a negative impact on your site or webapp to alter the native behaviour of the back button.
If the user refreshes the page in question it will add another record to the database, so I want to warn the user through an alert box if they really want to refresh the page and if they click ok then the page should be refreshed otherwise if they click cancel it won't be.
How to make this type of alert box appear when the browser's refresh button is clicked in a way that is cross browser compatible?
You can do it like this:
window.onbeforeunload = function() {
return "Data will be lost if you leave the page, are you sure?";
};
This would show a prompt to the user allowing them to cancel. It's not refresh specific, but for your purposes (like editing a question on SO) that doesn't seem to matter, it's loss of info no matter where you're leaving to.
There isn't a way to tie it to just the refresh action, but you may want to look into window.onbeforeunload. This will allow you to run a function that returns a string just before the page is unloaded. If this string is not empty, then a popup confirmation dialog, containing this string and some other boilerplate text provided from the browser.
For example:
window.onbeforeunload = function () {
if (someConditionThatIndicatesIShouldConfirm) {
return "If you reload this page, your previous action will be repeated";
} else {
//Don't return anything
}
}
Also, if the current page was loaded via a POST operation, then the browser should already display a confirmation box when the user tries to refresh it. As a general rule, any action that changes the state of the data on the server should be done through a POST request, rather than a GET.
All the answers are quite old, as of today 2020, according to HTML specification, you can do it this way.
Important Note: Custom text is not supported in most of the browsers now. (it was supported in older browsers).
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload
window.addEventListener('beforeunload', function (e) {
// Cancel the event
e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown
// Chrome requires returnValue to be set
e.returnValue = '';
});
There are two possible ways forward with this, both quite different.
One way would be to have an event handler bound to onbeforeunload event so that you can detect when the user is browsing away from the current page. If my memory serves me correctly however, onbeforeunload is not consistent across browsers (I don't think Opera responds to it IIRC, but have no way to currently test). Of course, this solution fails if the user turns off JavaScript.
The second and more robust way would be to implement the Post Redirect Get pattern which when used, prevents the data from being posted again when a user refreshes the page.
This is not possible. The best you can do is use the onbeforeunload event but that will fire on any event leaving the current page. It is not possible to target the refresh button specifically.
See e.g. this question on onbeforeunload
It might be better though to build a duplicate check into your database. That would catch accidental submissions using the "back" button as well.
An alternative would be using a random one-time token that gets built into the form. If two operations are attempted using the same token, you would stop it.
Quoting from official Mozilla site here, It is no longer supported to supply a custom message.
When this event returns (or sets the returnValue property to) a value other than null or undefined, the user will be prompted to confirm the page unload. In older browsers, the return value of the event is displayed in this dialog. Starting with Firefox 44, Chrome 51, Opera 38, and Safari 9.1, a generic string not under the control of the webpage will be shown instead of the returned string. For example:
Firefox displays the string, "This page is asking you to confirm that you want to leave - data you have entered may not be saved." (see bug 588292).
Chrome displays the string, "Do you want to leave this site? Changes you made may not be saved." (see Chrome Platform Status).
I am using asp.net 2.0 with c#.
i want a pop up to be displayed when user tries to close the browser and if user click on "no" [i.e. he don't want browser to be closed] then it prevent browser to get closed.
Please help.
Thanks
the code they use is
window.onbeforeunload=function() {
if (somereasonorother) return "You did not save your stuff"
}
Pointy, this is entirely possible, and it's done by many web pages for perfectly reasonable reasons.
Try something like this:
function areYouSure() {
return "Are you sure you want to leave this page?";
}
window.onbeforeunload = areYouSure;
You can try to attach yourself to the onbeforeunload event:
<body onbeforeunload="ConfirmClose();">
But I have to mention that it won't work on all browsers. The only ones that prompted something after I closed a window were Chrome, Firefox and Internet Explorer; Opera ignored the code in the JavaScript method.
This is mostly because some browsers trigger the onbeforeunload event only when you're trying to leave the current page by visiting another one, and not when you close the current window / tab.
Currently I am developing a web application for which I am using a pre-loader icon. What I want is that the pre-loader becomes visible every time the user navigates to another page or refreshes the page. So far I have the following solution:
window.onbeforeunload = function() { $("applicationdisabler").show(); };
For Safari and Firefox it works fine when the user clicks a link or refreshes the page. However in IE7 the div only becomes visible when the user clicks a link and NOT when the user refreshes the page.
The user can refresh the page by hitting F5 (on Windows) or any other possible way the browser provided.
Of course I have been looking for some workarounds already. The following code shows the alert in IE7, but the div still doesn't become visible.
window.onbeforeunload = function() { $("applicationdisabler").show(); alert("come on!"); };
The code of my div:
<div id="applicationdisabler"><img src="images/preloader.gif" /></div>
Hopefully someone can help me out.
You need to put the # before the id on the jQuery selector:
$("#applicationdisabler").show();
Why not use just use the onLoad listener instead? Although it would be slightly slower it should be more reliable.
Actually after a bit of looking around I'm not sure modifying the DOM makes any sense unless the onBeforeUnload handler returns false first - i.e. forces the user to stay on the same page.
As I understand it the onBeforeUnload event is fired just before the page is unloaded, so if you don't return false the browser will unload the page and DOM, and any JavaScript executed after that will be pointless.
That doesn't quite explain why JavaScript isn't executed properly in the onBeforeUnload function, but from what I've seen sites only use the window.alert or window.prompt dialogs to ask the user if they want to leave the site, and then often executing JavaScript if the user decides to stay.
Hence I'm guessing that some browsers may not allow DOM manipulation when this event is fired - since if the page is unloaded any DOM manipulation done is completely pointless.
So either:
Return false in your onBeforeUnload method, and then show your preloader (although this will stop navigation to the next page)
Use the onLoad event of the next page to show the preloader image instead
Also note: Opera versions 9.5 and below do not support this event (I'm unsure about later versions) but GMail does manage to catch the back button in Opera.
Possibly related is this security warning for IE7's implementation of the onBeforeUnload event - it's possible Microsoft patched it in a way that prevents the things you're trying to do. And I know IE6 and below don't allow commands like document.location='' in the onBeforeUnload handler for security reasons.