10
Author: Samantha Ming
Translator: Frontend Xiaozhi
Source: medium
There are dreams and dry goods. WeChat search [Moving to the World] Follow this brushing wisdom who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.

If you want to get the URL information of the site, then the window.location object is suitable for you! Use its attributes to get information about the current page address, or use its methods to redirect or refresh certain pages 💫

https://segmentfault.com/search?q=前小智#2
window.location.origin    → '"https://segmentfault.com'
               .protocol  → 'https:'
               .host      → 'segmentfault.com'
               .hostname  → 'segmentfault.com'
               .port      → ''
               .pathname  → '/search'
               .search    → '?q=前端小智'
               .hash      → '#2'
               .href      → 'https://segmentfault.com/search?q=前端小智#2'
window.location.assign('url')
               .replace('url')
               .reload()
               .toString()

window.location property

window.locationreturn value
.originSite main address (protocol + host name + port)
.protocolProtocol architecture ( http: or htts: )
.hostDomain name + port
.portport
.pathnameThe path followed by the'/' on the first page
.search? Followed by the query string
.hashThe part starting from #
.hrefFull URL

The difference between host and hostname

In the example above, you may notice that host and hostname return the same value. So why these attributes. Well, this has to do with the port number, let's take a look.

URL without port

https://segmentfault.com/search
window.location.host; // 'segmentfault.com'
window.location.hostname; // 'segmentfault.com'

window.location.port; // ''

URL with port

https://segmentfault.com/search"8080
window.location.host; // 'segmentfault.com:8080'
window.location.hostname; // 'segmentfault.com'

window.location.port; // '8080'

Therefore, host will include the port number, and hostname will only return the host name.

How to change URL properties

Not only can we call the location` property to retrieve URL information, we can also use it to set new properties and change the URL.

// 开始 'https://segmentfault.com/'

window.location.pathname = '/tidbits'; // 设置 pathname

// 结果 'https://segmentfault.com/tidbits'

Below is the complete list of properties you can change

// 事例
window.location.protocol = 'https'
               .host     = 'localhost:8080'
               .hostname = 'localhost'
               .port     = '8080'
               .pathname = 'path'
               .search   = 'query string' // (这里不用写 `?`)
               .hash     = 'hash' // (这里不用写 `#`)
               .href     = 'url'

The only attribute that cannot be set is window.location.origin , which is read-only.

Location object

window.location returns a Location object. It provides us with information about the current address of the page. But we can also access several ways Location object.

window.location          → Location
window.document.location → Location
document.location        → Location
location                 → Location

The reason we do this is that these are global variables in our browser.

clipboard.png

window.location vs location

The above four attributes all point to the same Location object. I personally prefer window.location and would actually avoid location . Mainly because location looks like an ordinary variable, and we may sometimes accidentally name it as a variable, which will overwrite global variables. for example:

// https://www.samanthaming.com

location.protocol; // 'https'

function localFile() {
  const location = '/sam';

  return location.protocol;
  // ❌ undefined
  //    b/c local "location" has override the global variable
}

I think most developers know that window is a global variable. This is unlikely to cause confusion. To be honest, I didn't know that location is a global variable until I wrote this article. It is recommended that you use window.location instead of other wordings.

window.location method

methodeffect
.assign()Load a new document
.replace()Replace the current document with a new document
.reload()Reload the current page
.reload()URL returned

Everyone said that there is no project to write on the resume, so I helped you find a project, and also included [Building Tutorial] .

window.location.toString

According to MDN :

This method returns the USVString URL, which is a read-only version of Location.href.

In other words, we can get the value of href

// https://www.samanthaming.com

window.location.href; // https://www.samanthaming.com
window.location.toString(); // https://www.samanthaming.com

assign vs replace

Both of these methods are redirecting or navigating to another URL. The difference is that assign saves the current page in the history, so the user can use the "back" button to navigate to this page. When using the replace method, it will not be saved. Let us look at an example.

Assign

1. 打开一个新的空白页
2. 输入 www.samanthaming.com (当前页)

3. 使用 `window.location.assign('https://www.w3schools.com')` 载入新页面
4. 按 "返回上一页"
5. 返回到了 👉 www.samanthaming.com

Replace

1. 打开一个新的空白页
2. 输入 www.samanthaming.com (当前页)

3. 使用 `window.location.assign('https://www.w3schools.com')` 载入新页面
4. 按 "返回上一页"
5. 返回到一个空白页

How to make the page redirect

There are 3 ways to redirect to another page.

window.location.href = 'https://www.samanthaming.com';

window.location.assign('https://www.samanthaming.com');

window.location.replace('https://www.samanthaming.com');

replace vs assign vs href

All three can be redirected, the difference lies in the history of the browser. href and assign will save the current page in the history, but replace will not. Therefore, if you want to create an experience where the navigation cannot return to the original page, please use replace 👍

The question now is href and assign . I prefer assign because it is a method, so it feels as if I am performing some operation. An additional benefit is that it is easier to test. I have written many Jest tests, so by using a method, it makes it easier to simulate.

window.location.assign = jest.fn();

myUrlUpdateFunction();

expect(window.location.assign).toBeCalledWith('http://my.url');

In the end, I hope that the cheat sheet can be helpful to you and can quickly bring you answers when needed.

Talents’ [Three Lian] is the biggest motivation for Xiaozhi to keep sharing. If there are any errors or suggestions in this blog, we welcome talents to leave a message. Finally, thank you for watching.


Original: https://morioh.com/p/b444d291bdfb

code is deployed, the possible bugs cannot be known in real time. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug .


communicate with

There are dreams and dry goods. search 160aafa9ac5ec8 [Great Move to the World] pay attention to this brushing wit who is still doing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi has been included, the first-line interview complete test site, information and my series of articles.


王大冶
68.1k 声望105k 粉丝