Should I use window.navigate or [removed] in JavaScript?

前端 未结 11 1589
小鲜肉
小鲜肉 2020-11-27 12:12

What\'s the preferred method to use to change the location of the current web page using JavaScript? I\'ve seen both window.navigate and document.location used. Are there an

相关标签:
11条回答
  • 2020-11-27 12:57

    You can move your page using

    window.location.href =Url;
    
    0 讨论(0)
  • 2020-11-27 13:02

    window.navigate not supported in some browser

    In java script many ways are there for redirection, see the below code and explanation

    window.location.href = "http://krishna.developerstips.com/";
    window.location = "http://developerstips.com/";
    window.location.replace("http://developerstips.com/");
    window.location.assign("http://work.developerstips.com/");
    

    window.location.href loads page from browser's cache and does not always send the request to the server. So, if you have an old version of the page available in the cache then it will redirect to there instead of loading a fresh page from the server.

    window.location.assign() method for redirection if you want to allow the user to use the back button to go back to the original document.

    window.location.replace() method if you want to want to redirect to a new page and don't allow the user to navigate to the original page using the back button.

    0 讨论(0)
  • 2020-11-27 13:13

    There really isn't a difference; there are about 5 different methods of doing it. However, the ones I see most often are document.location and window.location because they're supported by all major browsers. (I've personally never seen window.navigate used in production code, so maybe it doesn't have very good support?)

    0 讨论(0)
  • 2020-11-27 13:15

    window.location also affects to the frame,

    the best form i found is:

    parent.window.location.href
    

    And the worse is:

    parent.document.URL 
    

    I did a massive browser test, and some rare IE with several plugins get undefined with the second form.

    0 讨论(0)
  • 2020-11-27 13:15

    Late joining this conversation to shed light on a mildly interesting factoid for web-facing, analytics-aware websites. Passing the mic over to Michael Papworth:

    https://github.com/michaelpapworth/jQuery.navigate

    "When using website analytics, window.location is not sufficient due to the referer not being passed on the request. The plugin resolves this and allows for both aliased and parametrised URLs."

    If one examines the code what it does is this:

       var methods = {
                'goTo': function (url) {
                    // instead of using window.location to navigate away
                    // we use an ephimeral link to click on and thus ensure
                    // the referer (current url) is always passed on to the request
                    $('<a></a>').attr("href", url)[0].click();
                },
                ...
       };
    

    Neato!

    0 讨论(0)
提交回复
热议问题