问题
I'm using window.location.replace() with jQuery to redirect to a new page in wordpres if you got a older browser in either Internet explorer or Firefox due to my html5 layout.
var browser = jQuery.browser;
var version = browser.version.slice(0.3);
if ( browser.msie && version != "10.0" && version != '9.0' ) {
window.location.replace("http://crosscom.dk/update-browser");
}
if ( browser.mozilla && version != "17.0" && version != '16.0' && version != '15.0' ) {
window.location.replace("http://crosscom.dk/update-browser/");
}
The redirects works but since its loaded in the header in wordpres it keeps on looping everytime, you are sitting on: example IE 8.
So my question is following...
How can i kill the script or setup different parameters around my code to stop the script from looping after the browser got redirected once?
回答1:
The loop is caused because the redirection occurs no matter what page you are on, including the redirection target. To avoid a loop, test whether you are already in the redirect location.
There are a number of ways this could be achieved - the most efficient probably being a server side check and redirection. However, on the assumption that your knowledge level or deployment requirements mean that a JavaScript alternative is better, you could use the following code:
var redirectLocation = "http://example.com/example.html"; // Redirect destination
// Page location and redirectLocation should not be the same
if (window.location.href !== redirectLocation) {
// Redirect logic
}
Applying this directly to your own code example produces:
var browser = jQuery.browser;
var version = browser.version.slice(0.3);
var redirectLocation = "http://crosscom.dk/update-browser/"; // Redirect destination
// Page location and redirectLocation should not be the same
if (window.location.href !== redirectLocation) {
// Redirect logic
if ( browser.msie && version != "10.0" && version != '9.0' ) {
window.location.replace(redirectLocation);
}
if ( browser.mozilla && version != "17.0" && version != '16.0' && version != '15.0' ) {
window.location.replace(redirectLocation);
}
}
回答2:
Only include the script on pages where redirection is needed
来源:https://stackoverflow.com/questions/13683826/jquery-window-location-replace-keeps-looping