jQuery window.location.replace keeps looping

本秂侑毒 提交于 2019-12-25 02:19:01

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!