Difference between [removed].href and top.location.href

后端 未结 4 1922
轮回少年
轮回少年 2020-11-27 11:34

Can Anyone tell me the difference between window.location.href and top.location.href ?

And also where to use which one.

And which

相关标签:
4条回答
  • 2020-11-27 11:42

    top object makes more sense inside frames. Inside a frame, window refers to current frame's window while top refers to the outermost window that contains the frame(s). So:

    window.location.href = 'somepage.html'; means loading somepage.html inside the frame.

    top.location.href = 'somepage.html'; means loading somepage.html in the main browser window.

    Two other interesting objects are self and parent.

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

    window.location.href returns the location of the current page.

    top.location.href (which is an alias of window.top.location.href) returns the location of the topmost window in the window hierarchy. If a window has no parent, top is a reference to itself (in other words, window === window.top).

    top is useful both when you're dealing with frames and when dealing with windows which have been opened by other pages. For example, if you have a page called test.html with the following script:

    var newWin=window.open('about:blank','test','width=100,height=100');
    newWin.document.write('<script>alert(top.location.href);</script>');
    

    The resulting alert will have the full path to test.html – not about:blank, which is what window.location.href would return.

    To answer your question about redirecting, go with window.location.assign(url);

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

    top refers to the window object which contains all the current frames ( father of the rest of the windows ). window is the current window.

    http://www.howtocreate.co.uk/tutorials/javascript/browserinspecific

    so top.location.href can contain the "master" page link containing all the frames, while window.location.href just contains the "current" page link.

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

    The first one adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

    The second replaces the current history item so you can't go back to it.

    See window.location:

    • assign(url): Load the document at the provided URL.

    • replace(url): Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

    window.location.href = url;
    

    is favoured over:

    window.location = url;
    
    0 讨论(0)
提交回复
热议问题