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

I am trying to create a bookmarklet by passing the current URL as a parameter to another URL.

However, I found that this

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

not working as well

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

does. Besides the obvious difference that window.open opens another window and window.location.href changes the location, why does the latter work and the first just opens another window to its original location?

This is on Firefox. Oddly enough, everything works fine on Chrome.

Is this a safety thing?

+4
source share
1 answer

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

1. window.open() is a method in a window class

The call to the window.open() method actually creates a window object that can be stored in a variable and processed according to your program 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 opened an unwanted window is because you called window.open() , whose sole purpose is to open a new window.

2. window.location - a read-only property in the window class.

Although window.location is a read-only property, window.location has a built-in shortcut function that allows you to assign window.location , which has the same effect as calling window.location.assign() , which does not return window, but uses object of the root window to assign a new URL, whereby the newly assigned URL will be loaded in the browser window where javascript has been assigned to assign the location.

If you are bookmarking a script, then using window.location is the best way to capture the current URL of the window and assign it to the url string of your program.

The reason you may find that you get unexpected behavior in different browsers is because there is no official standard standard set for the window object, so every browser can implement it behind the scenes.

+5
source

Source: https://habr.com/ru/post/986465/


All Articles