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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With