Disable page refresh - javascript

I need to prevent users from refreshing a page.
I have scripted in such a way that there is no 'forward' or 'backward' movement required.
However, if one refreshes the page, 'everything' starts from the beginning.
To save everything before page refresh and restore them after is not ideal.
In order to prevent page refresh, I could use an alert();, but there are chances that the user might neglect the warning.
Any other choices...???

JavaScript cannot prevent the user from leaving the page (refresh counts as leaving the page), as it would violate the user's... whatever... Anyway, it's not possible. (even if you try, the browser will have tools to easily bypass any script you may write).

But if you will use pushState / replaceState from HTML5 to visually store the state of your webapp (and set the server to serve it from all those urls), you can navigate the user to the right place of an app even after refresh.

There is no way to prevent the user from refreshing the page. If you do not require that much data to be preserved, you can put in the URL (site.com/page.php?sort=2&x=3&y=4).
If you need a lot of data, you can only hope the user doesn't refresh the page. One way would be to, as you noted, display a dialog.
Oh, guess you could also use AJAX to store data server side and serve page to the user considering it's last state.

The best thing you can do is to ask for a confirmation by means of the window.onBeforeUnload event handler.
window.addEventListener('beforeUnload', function(e) {
var dialogText = 'Dialog text here';
e.returnValue = dialogText;
return dialogText;
});
Note that the handler function should assign a string value to the returnValue property of the Event object and return the same string.
For more information see MDN WindowEventHandlers.onbeforeunload.

Related

Enabling the back button without allowing manual changes through the URL

I have a jQuery Mobile application I'm developing. jQuery Mobile uses pushState by default to allow the browser's back button to work dynamically.
Now, my application is meant to change its pages dynamically, and the user should always arrive at the front page when loading the application.
The problem is, jQuery Mobile updates the page's hash in the URL whenever I go to a page in the application. Now, if the user enters the same hash in the application, jQuery Mobile will automatically take them to that page (when I'd want them to be handled by my code). Also, if they refresh the page, I'd like my code to take them back to where they should be, not directly moved to the hash the URL had.
To prevent this, I tried to add the following code in the mobileinit event:
$.mobile.hashListeningEnabled = false;
This works, but it also disables the pushState updates, which in turn breaks the back button, which I don't want to happen.
What would be the best way to allow users to use the back button while still not allowing manual movement between pages?
I don't have so much element to describe a possible and accurate solution for your problem, but an easy one should be this:
on every link on your page that take to another one attach a function like this:
$(DOMElem).on("click",function(){
sessionStorage["urlChangedByLink"] = "true";
});
On the same page you can try if there are no problem with this:
$( window ).on( "navigate", function( event, data ) {
if(sessionStorage["urlChangedByLink"] == "true")
$.mobile.hashListeningEnabled = true;
else
$.mobile.hashListeningEnabled = false;
});
Or this, on the other page you check if this storage variable exsist and than make your operation:
if(sessionStorage["urlChangedByLink"] == "true")
continue navigation...
else
window.history.back();
one option here is to set the data-url for each of your pages you simply add the attribute to your page div and set it equal to your home page that way the url for the page shown in the history doesnt have the hash values (or you could include your own values). the documentation on this is better explained in the jquery mobile documentation

To display the webpage again, Internet Explorer needs to resend

In my ASP.NET WebForms page I have a Modal window that pops up. The javascript code for displaying this modal window is as follows:
function OpenMailAddressWin(subscriberContactRelationGid, routeId, btn) {
window.showModalDialog("SubscriberSecondaryAddress.aspx" + BuildQueryStringValuesForSubscriber(subscriberContactRelationGid, routeId, returntxtReceiptDate().value), this, strWindowFeatures + ";scroll:no;dialogWidth:442px;dialogHeight:350px");
location.reload(true);
}
After the modal window is closed I need to refresh the parent page (hence the location.reload(true); statement at the end) in order for alterations made in the modal window to take affect.
Now the thing is that sometimes (not every time, infuriatingly) when I close this modal window I get a warning popup which says:
" To display the webpage again, Internet Explorer needs to resend the information you've recently submitted.
If you were making a purchase, you should click Cancel to avoid a duplicate transaction. Otherwise, click Retry to display the webpage again."
Any ideas why this is happening?
This is the double-submit problem in browsers.
When a page is loaded using POST request and you try to reload the page using location.reload(true);, the browser needs to send another POST request to the server and this may cause problems as POST is supposed to change state on the server. Therefore, the browser needs confirmation from the user. To solve this problem, we usually use POST-REDIRECT-GET pattern.
In your case, just simply using location.href = location.href should solve the problem as this will reload the page using GET.
This occurs when you try to return view(Model) from your POST request. Actually you cannot return a view from POST request because returning a view is supposed to be a GET operation and it must be done under GET request.
So after posting your data successfully and saving the data in database , you have to use ReturnToAction in your controller and return your final view from that action method.
Also If you want to refresh your page, you must use location.href = location.href instead of window.reload(), because location.href will get the data through GET request.
You can create a setTimeout function like this.
This will not give you any
setTimeout(function () {
window.parent.location.reload();
}, 100);
The Alert Message shows when refreshing a page in IE by using
That works... When you want to refresh the parent page.
This might be a valid soultion:
window.opener.location.href = window.opener.location.href;
I faced the same problem while calling modal window.
I removed location.reload and just returned true value from the function.
This solved my problem.
In my case I had something totally unrelated reloading the page, someone put some javascript code to reload the page in case of resize and it was always being triggered on document.ready, making it do the post request twice, so if none of the solutions here work just make sure that there isn't some random javascript reloading the page without you knowing about it, may be useful press F12 and check the network tab to see if something unexpected is being called.

Persisting DOM changes after clicking a link and then pressing the Back button

I'm using jQuery's appendTo() method to append items to an unordered list. When the user clicks another link, and then presses the Back button, the appended items disappear. Is there a way to persist those changes using JavaScript?
When hitting BACK, some browsers cache te previous (originally loaded) page. If you can regenerate the page with a fresh reload you can use cache-control 'no-store, no-cache, must-revalidate' to force this on a BACK.
Chrome wants no-store, and IE wants must-revalidate. For other browsers (and w3c) no-cache is enough.
Once your user navigates away from your page, the DOM is discarded. When your user hits the back button, they get a fresh copy of the HTML from your server (or from their cache).
So, you have one of 2 options:
The correct way would be to save the DOM state in a cookie (or session), and then on page load check if that cookie is present, and if so, append that info.
Since you have not provided enough information, I'm not exactly sure what you're trying to accomplish. So, if a cookie is not good enough, you might have to attach a click event to the link, and instead of just sending them off to that link, you'll first store the DOM in a variable var theDOM = $('html').clone(true);, and then load in the HTML for that link with an AJAX request.
You'll also have to inform the browser that your history state has changed. That can be accomplished with HTML5's new History API. In older browsers you can do something similar via the hash part of the URL (although in older versions of IE even that won't work). Then, when the user clicks the back button, you'll reload that DOM from your variable...
Either way, this is WAY too complicated. You're probably looking at this the wrong way. What are you trying to accomplish?
If you dont have any problem to use iframe then you can use it to preserve the previous data. On iframe load event write a js code which will take the preserved data within it and append it to desired element. This way when you navigate to next page and press back button the iframe will load and then the load event handler will do its job,

What to do when browser back button doesn't have the intended effect

I have a page where navigation is handled by hiding and showing preloaded divs when users click on links. But, the users think they've actually changed pages, so they click on their browser's "back" button trying to go back to the div that was previously hidden. But of course, they go back to the page from which they came.
What's the best way to handle this? 90% of the traffic is from a login page. Should I just sandwich a redirect page in between the two? How is this done? Can I just change the browser's back button behavior?
If you are already using jQuery, why not simply add a history manager like jq-bbq or the hashchange or history manager? (Or, if you want to really go all out, switch to a MVC JavaScript framework like Sammy.) That way, the back button will work as the user expects, rather than hacking around their expectations by blocking the back button or throwing in redirects. (Unless you have a good reason to, of course :-) )
If you use a browser history plugin like the jQuery UI one you end up changing the history so that the back button doesn't actually unload the page.
http://yoursite.com
-> User clicks something
-> new address bar reads http://yoursite.com/#/something
because of the hash mark when user goes back it goes back to http://yoursite.com which should inturn fire your show previous div function
read more about the available history manager plugins available for jQuery. There are quite a few. Most if not all provide available callback functions that you can specify.
On change of the state of your page, write a unique set of parameters to the hash of your URL. You can change this via JS without causing the page to reload.
Set a timer on the page that checks the current location hash repeatedly, and if it changes (i.e. the user presses the Back button) then update the state of your page to match the URL.
I have this scheme working to great effect in a local application.
The jQuery Address library is another great alternative.
http://www.asual.com/jquery/address/
You can set the URL for different application states, and get the URL 'parameters' when the page reloads.
Two ideas:
1) onbeforeunload. Ask the user if they want to really go back.
2) Sandwidch a redirect page. Login -> redirect -> your page. A single back click would take the user to your redirect page.
The second is kind of a pain in the neck for people who know what they're doing though. I think the Back button (and all standard navigational elements) should be messed with as little as possible.
I would go with onbeforeunload:
function sure()
{
event.returnValue = "sure?";
}
...
<BODY onbeforeunload="sure()">

Back Button and Refresh with AJAX

I need a solution for the page refresh and the back button when using AJAX.
I'm using simple javascript for the AJAX implementation.
If anybody could send a code snippet I would be very grateful.
If you're using jQuery, there's the history plugin.
Here's a solution that I've used in some of my pages. Add this to pages that changes are made at.
window.onbeforeunload = function() {
window.name = "reloader";
}
this triggers when you leave those pages. You can also trigger it if there were changes made. So that it won't unnecessarily reload the page that needs reloading.
Then on pages that you want to get reloaded on after a the browser "back" use.
if (window.name == "reloader") {
window.name = "no";
location.reload();
}
this will trigger a reload on the page you need reloading to.
essentially, you need to use & monitor the hash portion of the url...
http://.../path?parms#hashpart
Whan you change the hash, iirc window.location.hash , it won't reload the page, but your ajax can monitor, and respond to it.
The onbeforeunload event can be useful to guard against refreshing but it fires if you navigate away or refresh. If you require that users login to the app you can always show a generic message advising against navigating away and refreshing. If users click your app log out button set a var to disable the warning. Could probably also make a 'Close' button that does the same thing.
Try PathJS it does not require jQuery or any other additional lib.

Categories