window.open target _self v window.location.href?
JavascriptJavascript Problem Overview
I need to redirect the user using JavaScript. Which is the preferred method?
window.open("webpage.htm", "_self");
or
window.location.href = "webpage.htm";
Javascript Solutions
Solution 1 - Javascript
Definitely the second method is preferred because you don't have the overhead of another function invocation:
window.location.href = "webpage.htm";
Solution 2 - Javascript
Hopefully someone else is saved by reading this.
We encountered an issue with webkit based browsers doing:
window.open("webpage.htm", "_self");
The browser would lockup and die if we had too many DOM nodes. When we switched our code to following the accepted answer of:
location.href = "webpage.html";
all was good. It took us awhile to figure out what was causing the issue, since it wasn't obvious what made our page periodically fail to load.
Solution 3 - Javascript
As others have said, the second approach is usually preferred.
The two code snippets are not exactly equivalent however: the first one actually sets window.opener
to the window object itself, whereas the second will leave it as it is, at least under Firefox.
Solution 4 - Javascript
You can omit window
and just use location.href
. For example:
location.href = 'http://google.im/';
Solution 5 - Javascript
window.location.href = "webpage.htm";
Solution 6 - Javascript
> Please use this
window.open("url","_self");
> - The first parameter "url" is full path of which page you want to open. > - The second parameter "_self", It's used for open page in same tab. You want open the page in another tab please use "_blank".