Refreshing webpage after browser back button? - javascript

Let me begin by saying I do not want to "disable" or otherwise prevent the proper usage of the browser history buttons.
What I need is a javascript-based procedure (cross-browser compatible, hopefully) to refresh a webpage (staying on the same URL) after navigating to it using the back/forward buttons. This is necessary because during this process the server keeps track of the user's position/page, and if the user wants to jump back 3 pages I need to "inform" the server of the new location by reloading the page (or is there a better way to do it?) I already disabled caching through HTTP headers but this doesn't work for back/forward history, at least in Firefox 7.
Using jQuery is of course acceptable and desirable. I looked around a bit and found out about $(document).ready(). Now, please keep in mind I'm a complete javascript noob. I have zero experience, and the same goes for jQuery (I know what it does, I've looked at the docs, but that's about it). So I'm trying to understand how this works, but pages that mention this method seem to assume that the webdeveloper wants to modify the DOM from it, and there are a few quirks when you want to do that (load order and stuff). Since in my case I only need to refresh, it should hopefully be easier. So:
I understand this doesn't only run when you browse back, it also runs every time you load the page. How can I make sure I don't end up with an infinite loop? I want it to run once when I browse back, but not on load, after the automated refresh or otherwise. On a normal load I'd rather not have it running because the user would have to download each page twice, which is stupid!
Or is there a better way to do this? Any other ideas? Care to explain or point me in the right direction?
EDIT: I only need compatibility with:
Internet Explorer 8 or higher
Firefox 4 or higher
Recent-ish Chrome/Safari (I don't keep track of version numbers but why would someone not use up to date Chrome anyway?)

The best workaround I ever found for this problem is to use location.replace(), like so.
It does not directly address the problem from my original question; however, since that seems not to have a solution (for now), I recommend that everyone uses this client side function to protect the server side pages they do not wish to have executed again by a client using the back button. I'm sure this is better explained elsewhere on stackoverflow, but for the few people using my convoluted way of thinking to look the problem up, there you have it.

Its a bit of an abuse, but one of the ways of doing this would be to have your "proceed to next step" button as a form which POSTs. For example;
instead of
Proceed to next Page
you have
<form action = "foo" method = "POST"><input type = "submit" value = "Proceed to next page" /></form>
If the user hits back, they'll be forced to re-send their data to the server and your page would be refreshed. This would probably be really annoying to the user though!
But as i mentioned, major abuse of forms!
EDIT: This abuse will only work for certain scenarios though, you'll be the best judge of whether it's appropriate.

Related

IE settings through Javascript or jquery

Is there any possibility to set the Internet Explorer settings by running Javascript file..?
I want to set the following settings in IE through javascript/Jquery
Go to, ‘Tools’ -> ’Internet options’.
Under ‘General’ tab, click the ‘Settings’ button in the ‘Browsing History’ section.
Choose the radio button "Every time I visit the webpage".
Click ‘OK’ and restart the IE.
This is not possible - it'd be a bit of a security hole if sites were able to do this...
Firstly, the short answer is no: You can't do what you're asking for.
Javascript within the browser is heavily restricted to only being able to access resources for the actual page being viewed. This is an important security feature.
You cannot access other pages or other tabs. You cannot access parts of the browser UI outside of the page itself. You cannot run external programs.
Even if you could, the way you've described it wouldn't work anyway: The settings page you've described is specific to one particular version of IE. So your hypothetical program wouldn't work in any other browser or even any other version of IE.
However, more importantly, you need to ask yourself why you're asking for this.
The thing is that you're trying to solve a problem with your site. You've found something that resolves it, and you've asked a question about how to automate that. But you need to work backward a bit -- stop trying to work out how to automate this particular solution: you need to ask yourself whether there might be a different way of solving the original problem, which could be automated.
The fact is this: the config setting you're trying to change is for handling how the browser deals with caching of files. There are ways of changing the behaviour of caching that can be scripted by your site. You might want to look at questions like this one for example.
The lesson here is this: Don't simply ask how to do something; explain why you're trying to do it as well. There might be an alternative solution that's better than the one you've thought of.
No, it's not possible to do using JavaScript.
This is not what Javascript designed to do. There is only a way to read browser setting from JS - using signed scripts.

How to externally influence JavaScript running in a page

I'd like to be able to make the JavaScript I've got in a web page behave differently by doing something or setting something externally. So there'll be logic checking if(something) execute functionality one, else execute functionality two. I can think of three ways of doing this, but I don't like any of them enough to choose it. At least not unless I can see if there's another blindingly obvious way of doing it that's somehow escaping me at the moment.
Add a harmless query string to the URL (e.g. ?choose_functionality_one=true) and my logic can simply look in the page URL. The reason I don't like this is the case where my code is running inside a cross-domain iframe and I can't even access the page's URL (only the iframe's URL). Yes I could pass the query string to the iframe, but only if I have control over the parent page, and I don't.
Create a cookie in the domain of the page, and my logic can simply look for it in document.cookie. This could be done with a bookmarklet easily enough, and wouldn't suffer from the cross-domain problem, because I simply open a window/tab to the domain where my code is running and run the bookmarklet in that context. This is my front-runner choice at the moment.
Add something to the browser's useragent string and look for that in my logic. Pretty easy on Firefox via about:config, but is less easy with the other browsers, and downright difficult on the Mac. Also, on some browsers, once you've set a custom value, you lose the ability to have the UA get auto-updated when you get a browser update. Your UA's version info is stuck in time to where it was when you first custom'ed it.
Can anyone think of another way that via email/IM/phone I can say to someone "do this" and they'll see the page behave differently for troubleshooting purposes. For the general population who haven't done that though, it's running completely normally.
The simplest option seems to be to make a debug page on your site that will let the user turn the "debug" cookie on/off and then queue your regular site code off the existence of the cookie. I'd suggest making the debug cookie expire in a fairly short amount of time so people don't inadvertently leave it on.
This option has the advantages you are interested in (no user agent modification, works on all platforms, works with iframes) and I can see no disadvantages except that it wouldn't work if someone had cookies off, though a lot of the web won't work without cookies these days so that seems like something you could live with.
In addition, it's also the simplest for your users to use. You can just direct them to the right page on your site and all they have to do is click the desired button to turn it on or off. You can make the page very self explanatory which is certainly much easier than any of the other options.
OK, if you only control code and no HTML, then you could do either implement a keyboard shortcut key that would enable the debug mode by setting the cookie. The instructions could be something like this: put the keyboard focus in X and then press Ctrl-D.
Or, you could implement some special type of click (like a Ctrl-click on some object or in some page corner). In this case the instructions could be something like: Hold down the Ctrl-key and click on object X on the page.
Your JS code could implement either of those shortcuts. You could even put up a prompt (all with dynamically created HTML objects) when the special key/click was engaged to confirm turning the debug mode on or off.

Clever way to manage browser history

I'm trying to implement a decent navigation in a AJAX application. What I am doing right now is the following:
Every time a user clicks an AJAX link, the corresponding call is performed and the hash is changed.
Whenever a new page is loaded, I check whether the hash is present and make the corresponding AJAX call to update the page. This ensures that bookmarks will work as expected.
Every 500ms I check if the hash is changed and perform the corresponding AJAX call. This takes care of users pressing the back/forward buttons, albeit with a sligth delay.
The third point is a bit annoying: I'd rather not have a timeout every 500ms just to check the hash, as most of the time it will stay the same.
Is there a better way to manage this? I cannot think of any alternatives, but maybe I am missing something.
Please, do not point me towards ready-made solutions, unless you know they are based on a different mechanism.
There is the "hashchange" event, which is to be implemented in HTML5. I'm not sure how good support is now... IE8 supports it, and I think Mozilla have their own implementation in a recent release. Other than that, there is nothing I'm afraid. Checking exery x ms is the way everyone does it.
maybe this is an interesting read, it is a ready made solution for the exact thing you are doing.
and no, until the hashchange is properly supported in every browser (read: ie), you will have to check manually
Use this plugin: http://www.asual.com/jquery/address/
The jQuery Address plugin provides powerful deep linking capabilities and allows the creation of unique virtual addresses that can point to a website section or an application state. It enables a number of important capabilities including:
Bookmarking in a browser or social website
Sending links via email or instant messenger
Finding specific content using the major search engines
Utilizing browser history and reload buttons

Keeping an ajax web page functioning after hours of being idle

I have a one page web app so there is no page refreshing. Sometimes I leave the page open overnight and I come back in the morning and start interacting with it again. Usually I find I have to refresh. Javascript performs incorrectly - edit-in-place loads weird data, ajax calls don't fire... It's nothing to do with the backend, it seems to just be the browser dumping it's memory, or something. There're no sessions involved.
How does Google calendar stay open for 3 days and still fire event alerts?
I have a 'keep alive' call that fires every 5 seconds, in an attempt to keep the browser on its toes, but it hasn't helped. What's the trick? IS there a way to tell the browser to hold everything in memory forever?
(I'm sure this is addressed in numerous places on the web, but I can't figure out what to search for.)
Possible things to look at:
Test on a couple different browsers to see if they have the same problem.
If they do then its almost 100% certain something in your code.
Otherwise its probably something with your current browser and perhaps some interaction with some portion of your code.
Seems trivial but a lot of people over look this in javascript, but make sure you are deleteing/freeing anything you allocate with new.
If you use any 3rd party libraries consider updating them or checking their forums.
Good luck!
When you refresh the page do you need to do any authentication because of a timed-out session or anything ? Because if all you really need to do is hit F5 and you're good to go, I would suggest you create an 'idle' timer in your app that does a window.reload() every hour if there is no interaction (IOW reset that timer each time there is an interaction)
Hope this helps

Is it worth it to code different functionality for users with javascript disabled?

I'm currently building a project and I would like to make use of some simple javascript - I know some people have it disabled to prevent XSS and other things. Should I...
a) Use the simple javascript, those users with it disabled are missing out
b) Don't use the simple javascript, users with it enabled have to click a little more
c) Code both javascript-enabled and javascript-disabled functionality
I'm not really sure as the web is always changing, what do you recommend?
Degrade gracefully - make sure the site works without JavaScript, then add bells and whistles for those with JavaScript enabled.
Everyone else has committed good comments, but there are a few other considerations to make.
Sometimes the javascript will be hosted on a different domain, and be prone to timeout.
Sometimes that domain may become inacessible, while your site remains accessible. Its not good to have your site completely stack itself in this scenario.
For this reason, "blocking" scripts ( ie: document write inline ) like that present in google's tracker, should be avoided, or at very least, should go as late in the page as possible so the page renders whether or not the domain is timing out requests or not.
If you happen to be serving JS from a broken/malicious server, by intent or by accident, one can halt page rendering simply by having a script that serves that javascript which just calls "sleep(forever)" once its sent all the headers.
Some People Use NoScript
Like the above problem, sometimes the clients environment may block certain script sources, be it the users choosing, or other reasons ( ie: browser security satisfactions, odd antivirus/anti-malware apps ). The most popular and controllable instance of this is NoScript, and I myself paranoidly block some of the popular tracking/advertising services with it ( some proxy servers will do this too ).
However, if a site is not well designed, the failing of one script to load still executes code that was dependant on that script being present, which yeilds errors and stops everything working.
My recommendation is :
Use Firebug
Use NoScript and block out everything --> See Site still works
Enable core site scripts that you cant' do without for anything --> See site still works and firebug doesn't whine.
Enable 3rd party stuff --> See site still works and firebug doesn't whine.
There are a lot of other complications that can crop up, but satisfying the above 2 should solve most of them. Just assume that, for whatever reason, one or more resources that comprise a page are viable to spontaneously disappear ( they do, all the time ), and you want the page to "survive" this problem as amicably as possible. For the problems that may persist for < 10 seconds, its not so bad, refresh the page and its fixed, but if its a problem that can occur, and severley hamper usability for an hour or more at a time.
In essence, instead of thinking "oh, theres the edge case users that don't have javascript", try thinking more a long the lines of "its really easy to have something go wrong, and have ALL of our users with broken javascript. Ouch! Lets try make it so we dont' really hose ourself when that does happen"
( I've seen IE updates get rolled out and hose javascript for that entire browser until the people whom wrote the scripts find a workaround. Losing all your IE customers is not a good thing )
:set sarcasm
:set ignoreSpelling
:set iq=76
Don't worry, its only a 5% Niché Market
Nobody cares about targeting Niché markets right? All those funny propeller heads running lynx in their geeky stupid linoox cpus, spending all their time on the intarwebs surfing because they have nothing better to do with their life or money? the crazy security paranoid nerds disabling javascript left and right because they don't like it?
Nobody wants them as your primary customer now do they?
Niché markets. Pfft. Who cares!
:set nosarcasm
Consider your audience
"Degrade gracefully" is generally the best answer. But lots of sites now depend on JS - especially AJAX.
Consider your audience. If your site is aimed at extremely tech-savvy people, the chances of them not having javascript are small, and you can notify them to turn it on if necessary.
If your audience may access your site with mobile devices, don't assume they have JavaScript, and don't even assume they support CSS properly. Aim to degrade gracefully all the way down to bare HTML.
I've learned a lot from my question: What's With Those Do-Not-Use Javascript People
Go with Ajax and Web 2.0. It's the way the web is going and it's wonderful. Isn't Stackoverflow great to be on? It's not quite as nice with your Javascript turned off.
Once you have your site ready, but before you let it go live, test it with Javascript off, and just add whatever you feel you need to make your site appear and function to them. You only need to add what you feel is essential.
Remember, except for visually impared people using screen readers, the others have chosen to turn javascript off. They can also choose to trust your site and turn javascript on for your site if they want to use all the functionality you have. It really is their choice.
As other have said, it should "degrade gracefully".
In other works, it must work without Javascript (period). It doesn't have to work well. The folks who've disabled Javascript know the limitations that causes and have accepted them. But if you are trying to sell them something, it's important that they can still buy it.
On the site I'm designing, there's a javascript-based fly-out menu. With Javascript off, all the flyouts are always open. It doesn't look as cool as it would with JS, but it can still be used to navigate the site.
It depends on how much time you have to develop and maintain both solutions, and how much the non-javascript users are worth to you.
My e-commerce site relies heavily on javascript, and in over a year and a half, I've not received a single complaint.
In fact, I don't think I've seen a single visitor with javascript disabled in any of logs since I started.
That doesn't mean they're not out there. It just means that either (a) they're a tiny percentage, (b) they're not interested in what I'm selling, or (c) both of the above.
Code your web site with support for the bare minimum kind of browser. Then more people can use your site without frustration even if they don't have all the bells and whistles--like Flash, Javascript, and Java--enabled. It may not be practical to continue support for ancient browsers, say Netscape Navigator 4, because a user can be reasonably expected to keep their computer up-to-date. However, features like Javascript, Flash, and Java can be security holes in old or modern browsers, as well as being an annoyance.
Neither of my parents keep Javascript or Flash enabled because they've had too many experiences with them slowing down their already slow connection, crashing their browsers, or being more of an annoyance on sites that use it stupidly (which is a lot of them...) than a useful feature. It's just bad design if, for example, your form requires an AJAX call be made and you can't actually hit a submit button to send the form when Javascript is disabled.
My mother was recently quite frustrated to discover that she is now unable to click through eBay results pages because each one requires Javascript. The only way she can see the next page of results is to turn on Javascript or to show more results per page. Now what reason would there be for page links to require Javascript while the 'results per page' links are just plain links? They should all be plain old HTML links. Maybe Javascript could be used to add some whiz-bang to the navigation, but a user should not be punished with a bad interface for having Javascript disabled. It's stupid on eBay's part, and it causes undue hassle for their users.
I am one of those that uses 'No-Script.' And I can tell you that sites that use javascript and don't work without it enabled is extremely annoying, stackOverflow... No we don't expect it to be very fancy, if I upvote load a new page that says "Thank you."
We expect to be able to use the site with reasonable limitations, don't ever display a page that says JS must be enabled, though, even if the site is crap without it. And yes if your site convinces us to stay we will enable. A function that isn't in common use on the site can also require javascript.
Please note that your site should also look good with no JS or CSS, if nothing else it is good for Bots.
As others have pointed out some phones don't have JS, this is changing but another good reason to have reasonable non-JS. I suggest code with non-JS and add JS after the former works, there are good ways where JS can work with the non-JS layout.
It helps me in my implementations to think about it as "progressive enhancement" rather than graceful degradation. Degradation often leads you to figure out how to make it work w/o js after it is implemented, instead of making a baseline and enhancing with js.
It is essential to at least test your website is functional when JavaScript is turned off.
As orip says, degrading gracefully is very important. It should be vital that your page both looks nice and functions when JavaScript is disabled.
For a standard web site that is primarily intended for conveying information, degrade gracefully always.
For web applications:
When building a web application for a standard internet audience, I would keep the three following facts in mind:
95%-97% of potential users will have JavaScript enabled.
At times established users will need to access functionality when JavaScript is not available.
3%-5% of potential users will have JavaScript intentionally disabled.
Given fact one, if you believe that building a JavaScript reliant web application will deliver a superior user experience, then by all means do it. Doing so may help you accumulate users.
However, given fact two, you should always provide a means by which your users can access core functionality without JavaScript. Do you need to offer every single feature? Probably not. But a user should be able to get his or her work done. This will keep your users happy when they find themselves temporarily without JavaScript.
Given fact three, I would also provide an in depth tour as an attempt to entice these users to enable JavaScript.
As an aside, one of my most favorite web applications, Remember The Milk follows this approach. Also, Google's Calendar application is unusable without JavaScript. So JavaScript reliant web apps are on the rise and that trend is probably unstoppable. In my opinion this is a good thing.
(Do keep in mind that JavaScript make Accessbility a bigger problem than it is already. Please do make an effort to make your apps usable by those with disabilities.)
As said before, it depends on your target audience.
If I'm part of it, you want to make sure that your site works (if not ideally) on my phone, and that it gives me reason to turn Javascript on when I surf there with it off. Nobody expects full functionality with Javascript disabled, and anybody who uses their phone to access websites expects some issues, but you need to at least provide teasers. For a web store, make sure customers can see at least some merchandise anyway, even if they can't buy without Javascript.

Categories

Resources