How can I reload the page using JavaScript?
I need a method that works in all browsers.
JavaScript 1.2 and newer
window.location.reload();
// If we needed to force the document to be fetched from the
// web server again (such as where the document contents
// change dynamically but cache control headers are not
// configured properly), Firefox supports a non-standard
// parameter that can be set to true to bypass the cache:
//window.location.reload(true);
JavaScript 1.1
window.location.replace(window.location.pathname + window.location.search + window.location.hash);
// does not create a history entry
JavaScript 1.0
window.location.href = window.location.pathname + window.location.search + window.location.hash;
// creates a history entry
location.reload();
See this MDN page for more information.
If you are refreshing after an onclick then you'll need to return false directly after
location.reload();
return false;
I was looking for some information regarding reloads on pages retrieved with POST requests, such as after submitting a method="post" form.
To reload the page keeping the POST data, use:
window.location.reload();
To reload the page discarding the POST data (perform a GET request), use:
window.location.href = window.location.href;
Hopefully this can help others looking for the same information.
You can perform this task using window.location.reload();. As there are many ways to do this but I think it is the appropriate way to reload the same document with JavaScript. Here is the explanation
JavaScript window.location object can be used
to get current page address (URL)
to redirect the browser to another page
to reload the same page
window: in JavaScript represents an open window in a browser.
location: in JavaScript holds information about current URL.
The location object is like a fragment of the window object and is called up through the window.location property.
location object has three methods:
assign(): used to load a new document
reload(): used to reload current document
replace(): used to replace current document with a new one
So here we need to use reload(), because it can help us in reloading the same document.
So use it like window.location.reload();.
Online demo on jsfiddle
To ask your browser to retrieve the page directly from the server not from the cache, you can pass a true parameter to location.reload(). This method is compatible with all major browsers, including IE, Chrome, Firefox, Safari, Opera.
Try:
window.location.reload(true);
The parameter set to 'true' reloads a fresh copy from the server. Leaving it out will serve the page from cache.
More information can be found at MSDN and in the Mozilla documentation.
This works for me:
function refresh() {
setTimeout(function () {
location.reload()
}, 100);
}
http://jsfiddle.net/umerqureshi/znruyzop/
To reload a page using JavaScript, use:
window.location.reload();
If you put
window.location.reload(true);
at the beginning of your page with no other condition qualifying why that code runs, the page will load and then continue to reload itself until you close your browser.
location.href = location.href;
Shortest (more)
history.go()
This should work:
window.location.href = window.location.href.split( '#' )[0];
or
var x = window.location.href;
x = x.split( '#' );
window.location.href = x[0];
I prefer this for the following reasons:
Removes the part after the #, ensuring the page reloads on browsers that won't reload content that has it.
It doesn't ask you if want to repost last content if you recently submit a form.
It should work even on most recent browsers. Tested on Lasted Firefox and Chrome.
Alternatively, you may use the most recent official method for this task
window.location.reload()
The Javascript reload() method is used to reload the current document or URL. The javascript location.reload(true) method work just like reload button in your browser. By default, the JS reload() method reloads the page from the cache, however you may force it to reload the page from the server side by setting the forceGet parameter to true: location. reload(true).
Source: https://www.coderepublics.com/JavaScript/javascript-location-reload-true.php
What about Depricated?
It is only the reload with forcedReload which is now deprecated. But to avoid depricated error you can use location.reload() without the forceReload flag.
Related
Today, I noticed this issue in IE11.
A simple JavaScript redirect (made via location.href = 'newhost...';) causes the browser to crash.
Does anyone have any idea how can this be fixed?
If it helps this happened using ContactForm7 on wordpress using this method: http://contactform7.com/redirecting-to-another-url-after-submissions/
Internet Explorer doesn't always play nice with location.href or window.location.href in javascript. i.e. more so the href function...
Try using:
window.location.assign("newhost.."); // or
window.location = "newhost..";
window.location:As described in more detail here.The Window.location read-only property returns a
Location object with information about the current location of the
document.
Though Window.location is a read-only Location object, you can also
assign a DOMString to it. This means that you can work with
document.location as if it were a string in most cases:
window.location = 'http://www.example.com' is a synonym of
window.location.href = 'http://www.example.com'.
There is a solution to this problem in a WordPress forums post here: https://wordpress.org/support/topic/redirection-crashes-ie-11-perfect-for-all-others
KookRoss says:
I found a solution to this, its an ugly one but it does get around the
issue for me.
on_sent_ok:
"$("#post-440").empty();window.location.replace('https://www.url.com.au/thank-you/');"
Where post-440 is the ID of the div which surrounds the form. Put
simply your post led me to the belief that IE is somehow passing that
form again before doing the redirection, this uses jQuery to clear
that entire page of content (including the form) before doing the
redirection.
Its a hack way to get around the IE issue but so far its working in
all browsers for me including IE11.
If you still get this error even using Assign in IE 11 when redirect from an event, you can use:
setTimeout(function ()
{
window.location.assign("newhost...");
}, 100);
To get around the problem
I'm working on a website that uses AJAX loading with some jQuery animations.
With JavaScript, I grab the href from a dynamically generated link to a PHP-based page, and then add that href to URL (after the inevitable #/) .
So far so good, except if a user bookmarks the page and tries to access it, that user will arrive to the home page, instead of the page he/she expected to access.
So, when a page is accessed directly, not by clicking on the internal link of the website, I want to remove #/ from the url, but keep everything after it, so that URL that was bookmarked like this:
http://www.mysite.com/#/somepage
gets rewritten as this:
http://www.mysite.com/somepage
THEN, after the proper page ( http://www.mysite.com/somepage ) finished loading, I want to stick #/ back into its former place in URL ( http://www.mysite.com/#/somepage ), without reloading the page (which, thanks to a clever snippet I'm using, will ensure that the rest of the navigation works the way it should.)
So:
Before page loads, check URL and if it has #/, remove it.
Load page located at hash-less url
Redisplay the url with #/, without reloading the page.
Is it even doable? If yes, I'd be grateful for a lesson.
What you are trying to do is doable but an utter PITA to maintain, and it will not be available on all browsers. That aside, the key resides in the history object relatively recently extended to add a new set of "tricks". Its full doc is available from MDN.
What you are after to do this is the replaceState command. Reads as follows:
Updates the most recent entry on the history stack to have the specified data, title, and, if provided, URL. The data is treated as opaque by the DOM; you may specify any JavaScript object that can be serialized. Note that Firefox currently ignores the title parameter; for more information, see manipulating the browser history.
This will allow you to replace your current page in the history of the browser, but not in the URL. The URL will be exactly as you have it - with the hash. No point changing it considering your solution.
However, you will have to make sure that your hashless page redirects to the hash-present page for clients with the history object, for consistency. That's the only requirement.
Before page loads, check URL and if it has #/, remove it.
Not possible. The fragment id is not sent to the server, so you can only access it with client side code and that requires the page to load (or at least to start loading).
Load page located at hash-less url
Redisplay the url with #/, without reloading the page
Use XMLHttpRequest to get the data, DOM to change the document to use it, and the history API to change the URL in the address bar.
As has been pointed out in one of the answers, you can't remove hash before your page loads.
However, once the page started loading, the manipulation described in the question is possible.
Here's one way to do it.
// Remove the hash and reload the page at url without hash
if (window.location.href.indexOf('/#/')>=0) {
window.location = window.location.href.replace(/\/#\//, '/');
}
Once the new page started loading, you can use history.pushState to update the URL display:
if ((window.location.href.indexOf('/#/')<1) && (location.pathname != "/")) {
history.pushState({}, "page x", location.protocol + '//' + location.host + '/#' + location.pathname);
}
You gotta keep in mind though that pushState is only available for browsers started with Gecko 2.0, so placing the hash back into the url will not work in older browsers, period.
This may lead to some unfortunate situations. For example, hypothetically, your url http://www.mywebsite.com/somepage gets indexed by a search engine. A user clicks on that link, accessing your website in an older browser that doesn't support pushState, and then clicks on some other link when browsing your AJAX-enabled website. That user is likely to arrive to
http://www.mysite.com/somepage/#/someotherpage
And then, as the user keeps clicking, it will only keep getting worse:
http://www.mysite.com/somepage/#/someotherpage/#/yetanotherpage/#/andsoon/#/andsoforth/
So what you probably need is something to make sure that your hashes don't keep propagating.
You can also wrap your hash removing / replacing code in a conditional:
if (history.pushState) {
// add hash
} else {
// provide some alternative
}
Finally, look into these two resources. You may not need the hash at all: History.js and jQuery Address.
I am using the below to set my iFrames content, but will setting the same url a second time refresh the content in all browsers? Or do I need to use http://targeturl.com/targetpage?random=currenttime to prevent caching and cause a reload?
function setIframeSource(Iframe, targetUrl){
var Elem = document.getElementById(Iframe);
Elem.src = targetUrl;
}
it will definitely reload the page, but caching might be handled differently depending on the browser/version/server and even user settings, so if you want to refresh it properly - use cachebuster (time).
You shouldn't need to force a cache refresh like this on web pages, unless you know that that particular web page needs a forced cache refresh.
If you needed to append a cache refresh querystring to every web page in an iframe, then this would be true for accessing any web page in your browser, which obviously isn't the case.
I believe it shouldn't refresh the iFrame if the URL is the same or only the fragment identifier (# part) changes, but you might need to test this on a few browsers (particularly IE which never seems to follow specs)
If you are setting the URL with Javascript, why don't you call the reload() method of the iframe? Eseentially, that iframe is a window, and contains the same methods you would have for a normal window object.
I have found numerous answers on how to extract the URL without the parameters.
How do you rewrite the URL in the address bar without causing the page to reload with the new URL?
shortURL = top.location.href.substring(0, top.location.href.indexOf('?'));
top.location.href = shortURL // Causes redirect
The goal is to extract the parameters in Javascript but not display them in the address bar.
In modern browsers with support for the History object, you can use either history.replaceState() or history.pushState() to change the current URL without changing the current page. There are limitations on what you can change (for example, you cannot change the domain/origin this way for security reasons).
See here for a summary of these methods.
The browser history is a recording of where you have been in your browsing session. .replaceState() allows you to replace the current item in the history list with a different one. .pushState() adds a new item to the browser history and both change the URL displayed in the browser URL bar without reloading the page. You select which method to use depending upon how you want the browser's "back" button to behave for this particular page entry.
Note: These APIs are supported in IE 10 and later.
In older browser versions without support for the history API, the only part of the URL you can change without reloading the page is the hash tag (the part after a # symbol) at the end of the URL.
In html5, rewriting url without reloading the page is possible (still you can not change the domain name for security reasons), using history api you can write:
history.replaceState("object or string", "title", "/another-new-url");
in which the first two parameters are somehow arbitrary, and the third parameter is the new url (not including domain name). If you want to enable back button for returning to previous url, use pushState instead of replaceState above. Read more about these functions in this blog post.
Regarding browser support, it is supported in recent Firefox and Chrome versions, but only in IE10+, which is not very common yet. For details see compatibility matrix or browser implementation details.
You can't change the value in the address bar without redirecting. That would be a phishing scammer's dream come true!
You can, however, change the fragment identifier: (in JavaScript, the window.location.hash value)
<!DOCTYPE html>
<html>
<head>
<title>This is a test</title>
<script>
window.onload = function() {
window.location.hash = "Loaded!";
document.getElementById("click-me").onclick = function() {
window.location.hash = "Click!";
document.getElementById("click-me").onclick = function() {
window.location.hash = "Clicked AGAIN!";
};
};
}
</script>
<body>
<div>
<input type="button" id="click-me" value="click me!" />
</div>
</body>
</html>
But changing the query string will redirect the page.
You might be able to use the new pushstate that is part of the HTML 5 history API, which allows you to change the URL without actually reloading the browser.
Check http://badassjs.com/post/840846392/location-hash-is-dead-long-live-html5-pushstate for a quick example, and http://diveintohtml5.info/history.html for more in depth examples and limitations:
I don't think that there is a possibility for that, I mean you probably could rewrite the URL after its loaded and add return false, so you prevent the reload but otherwise you would have to do a form POST on the url to achieve that no parameter is shown.
What is the difference between JavaScript's
window.location.href = window.location.href
and
window.location.reload()
functions?
If I remember correctly, window.location.reload() reloads the current page with POST data, while window.location.href=window.location.href does not include the POST data.
As noted by #W3Max in the comments below, window.location.href=window.location.href will not reload the page if there's an anchor (#) in the URL - You must use window.location.reload() in this case.
Also, as noted by #Mic below, window.location.reload() takes an additional argument skipCache so that with using window.location.reload(true) the browser will skip the cache and reload the page from the server. window.location.reload(false) will do the opposite, and load the page from cache if possible.
If you say window.location.reload(true) the browser will skip the cache and reload the page from the server. window.location.reload(false) will do the opposite.
Note: default value for window.location.reload() is false
The difference is that
window.location = document.URL;
will not reload the page if there is a hash (#) in the URL (with or without something after it), whereas
window.location.reload();
will reload the page.
If you add the boolean true to the reload
window.location.reload(true) it will load from server.
It is not clear how supported this boolean is, W3Org mentions that NS used to support it
There MIGHT be a difference between the content of window.location.href and document.URL - there at least used to be a difference between location.href and the non-standard and deprecated document.location that had to do with redirection, but that is really last millennium.
For documentation purposes I would use window.location.reload() because that is what you want to do.
As said, modifying the href when there is a hash (#) in the url would not reload the page. Thus, I use this to reload it instead of regular expressions:
if (!window.location.hash) {
window.location.href = window.location.href;
} else {
window.location.reload();
}
Came across this question researching some aberrant behavior in IE, specifically IE9, didn't check older versions. It seems
window.location.reload();
results in a refresh that blanks out the entire screen for a second, where as
window.location = document.URL;
refreshes the page much more quickly, almost imperceptibly.
Doing a bit more research, and some experimentation with fiddler, it seems that window.location.reload() will bypass the cache and reload from the server regardless if you pass the boolean with it or not, this includes getting all of your assets (images, scripts, style sheets, etc) again. So if you just want the page to refresh the HTML, the window.location = document.URL will return much quicker and with less traffic.
A difference in behavior between browsers is that when IE9 uses the reload method it clears the visible page and seemingly rebuilds it from scratch, where FF and chrome wait till they get the new assets and rebuild them if they are different.
A difference in Firefox (12.0) is that on a page rendered from a POST, reload() will pop up a warning and do a re-post, while a URL assignment will do a GET.
Google Chrome does a GET for both.
Using JSF, I'm now having the issue with refresh after session is expired: PrimeFaces ViewExpiredException after page reload and with some investigation I have found one difference in FireFox:
Calling window.location.reload() works like clicking refresh icon on FF, it adds the line
Cache-Control max-age=0
while setting window.location.href works like pressing ENTER in URL line, it does not send that line.
Though both are sent as GET, the first (reload) is restoring the previous data and the application is in inconsistent state.
No, there shouldn't be. However, it's possible there is differences in some browsers, so either (or neither) may not work in some case.
from my experience of about 3 years, i could not find any difference...
edit : yes, as one of them here has said, only passing a boolean parameter to window.location.reload() is the difference.
if you pass true, then the browser loads a fresh page,
but if false, then the cache version is loaded...
In our case we just want to reload the page in webview and for some reasons we couldn't find out why!
We try almost every solution that has been on the web, but stuck with no reloading using location.reload() or alternative solutions like window.location.reload(),
location.reload(true), ...!
Here is our simple solution :
Just use a < a > tag with the empty "href" attribution value like this :
< a href="" ...>Click Me</a>
(in some cases you have to use "return true" on click of the target to trigger reload)
For more information check out this question :
Is an empty href valid?
window.location.href, this as saved my life in webview from Android 5.1. The page don't reload with location.reload() in this version from Android.