Home > Web Front-end > JS Tutorial > A cheat sheet for window.location to help you better understand and solve address path problems! !

A cheat sheet for window.location to help you better understand and solve address path problems! !

青灯夜游
Release: 2021-05-24 11:14:22
forward
1760 people have browsed it

This article shares a cheat sheet for window.location to help you better understand and solve address path problems! ! It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A cheat sheet for window.location to help you better understand and solve address path problems! !

If you want to get the URL information of the site, then the window.location object is suitable for you! Use its properties to get information about the current page address, or use its methods to do some page redirection or refresh

https://segmentfault.com/search?q=frontend小智#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'
Copy after login
window.location.assign('url')
               .replace('url')
               .reload()
               .toString()
Copy after login

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 '/' on the first page
.search? followed by the query string
.hashThe part starting from
.hrefFull URL

The difference between host and hostname

In the above example, you may notice that host and hostname return the same value. So why these properties. Well, it's about the port number, so 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; // ''
Copy after login

URL with port

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

window.location.port; // '8080'
Copy after login

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

How to change the URL attribute

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

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

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

// 结果 'https://segmentfault.com/tidbits'
Copy after login

Here 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'
Copy after login

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

Location object

window.locationReturns a Location object. It gives us information about the current address of the page. But we can also access the Location object in several ways.

window.location          → Location
window.document.location → Location
document.location        → Location
location                 → Location
Copy after login

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

A cheat sheet for window.location to help you better understand and solve address path problems! !

window.location vs location

The above four properties all point to the same Location object. I personally prefer window.location and would actually avoid using location. Mainly because location looks like a normal variable, and we may sometimes accidentally name it as a variable, which will override the global variable. 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
}
Copy after login

I think most developers know that window is a global variable. This way confusion is less likely to occur. To be honest, I didn't know location was a global variable until I wrote this post. It is recommended that you use window.location instead of other writing methods.

window.location method

MethodFunction
.assign()Load a new document
.replace()Replace the current document with the new one Document
.reload()Reload the current page
.reload()Return URL

window.location.toString

根据 MDN :

此方法返回 URL 的 USVString,它是 Location.href 的只读版本。

换句话说,我们可以这样得到 href 的值:

// https://www.samanthaming.com

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

assign vs replace

这两种方法都是重定向或导航到另一个URL。 区别在于assign 是将当前页面保存在历史记录中,因此用户可以使用“后退”按钮导航到该页面。 而使用replace方法时,不会保存它。 让我们来看一个例子。

Assign

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

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

Replace

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

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

如何让页面重定向

如何重定向到另一个页面,有3种方法。

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

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

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

replace vs assign vs href

这三个都可以重定向,区别在于浏览器的历史记录。 hrefassign 会把当前页面保存在历史记录中,而replace则不会。 因此,如果你想创建一种导航无法回到原始页面的体验,请使用replace

现在的问题是hrefassign。 我更喜欢assign,因为它是一种方法,因此感觉好像我正在执行一些操作。 还有一个额外的好处是它更易于测试。 我已经编写了许多Jest测试,因此通过使用一种方法,它使其更易于模拟。

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

myUrlUpdateFunction();

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

最终希望备忘单,希望能对你有所帮助,在需要的时候,能快速给你带来答案。

英文原文地址:https://morioh.com/p/b444d291bdfb

作者:Samantha Ming

转载自:https://segmentfault.com/a/1190000040017009

译者:前端小智

更多编程相关知识,请访问:编程教学!!

The above is the detailed content of A cheat sheet for window.location to help you better understand and solve address path problems! !. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template