Difference between window.location.href and top.location.href
Solution 1:
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);
Solution 2:
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
.
Solution 3:
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 theassign()
method is that after usingreplace()
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;