Rebecca
Rebecca

Reputation: 14402

window.open target _self v window.location.href?

I need to redirect the user using JavaScript. Which is the preferred method?

window.open("webpage.htm", "_self");

or

window.location.href = "webpage.htm";

Upvotes: 99

Views: 234471

Answers (6)

Mohammed Shaheen MK
Mohammed Shaheen MK

Reputation: 1219

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".

Upvotes: -3

Garry Polley
Garry Polley

Reputation: 4443

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.

Upvotes: 40

davidhiggins
davidhiggins

Reputation: 99

You can omit window and just use location.href. For example:

location.href = 'http://google.im/';

Upvotes: 6

Frédéric Hamidi
Frédéric Hamidi

Reputation: 262929

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.

Upvotes: 23

Jacob Relkin
Jacob Relkin

Reputation: 163238

Definitely the second method is preferred because you don't have the overhead of another function invocation:

window.location.href = "webpage.htm";

Upvotes: 103

Or Weinberger
Or Weinberger

Reputation: 7472

window.location.href = "webpage.htm";

Upvotes: 2

Related Questions