Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between window.open(url) and window.location.href = url on Firefox?

I am trying to build a bookmarklet, feeding the current url as a parameter to another url.

However I am finding out that this

javascript:(function(){window.open("http://www.somesi.te/some/thing?url="+encodeURIComponent(window.location.href))})()

does not work, while this

javascript:(function(){window.location.href = "http://www.somesi.te/some/thing?url="+encodeURIComponent(window.location.href)})()

does. Apart from the obvious difference that window.open opens another window, and window.location.href changes location, why does the latter work, while the former just opens another window to the original location?

This is on Firefox. Funnily enough, on Chrome things work fine.

Is this a security thing?

like image 910
simone Avatar asked Oct 28 '14 09:10

simone


Video Answer


1 Answers

The difference between window.open() and window.location.href is that open() is a method of the window class, and window.location is a property of the window class.

1.window.open() is a method on the window class

Calling the window.open() method actually creates a window object, which can be held in a variable and manipulated according to your program's requirements.

To demonstrate that window.open() actually returns a window object, consider the following code:

var mywindow = window.open("http://google.com");
mywindow.name = "Awesome Window";
console.log(typeof(mywindow)); // --> "object"
console.log(mywindow.name); // --> "Awesome Window"

The reason your code was opening an unwanted window, is because you were calling window.open(), whose sole purpose in life is to open a new window.

2. window.location is a read-only property on the window class.

Although window.location is a read-only property, the window.location has a built-in shortcut feature that allows window.location to be assignable, which has the same effect as calling window.location.assign(), which does not return a window object, but uses the root window object to assign a new url to, causing the newly-assigned url to be loaded in the browser window where the javascript assigning the location was called.

If you are creating a bookmarket script, then using window.location is the better way of grabbing the current window's url and assigning it to your program's url string.

The reason why you might find that you are getting unexpected behavior in different browsers, is that there is no official public standard set for the window object, so how each browser chooses to implement it behind the scenes may vary.

like image 113
radiovisual Avatar answered Oct 09 '22 10:10

radiovisual