search
HomeWeb Front-endJS TutorialDetailed explanation of window.location object in JS (cheat sheet)

Detailed explanation of window.location object in JS (cheat sheet)

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

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.location Return value
.origin Site main address (protocol host name port )
.protocol Protocol architecture (http: or htts:)
.host Domain name port
.port Port
.pathname The path followed by '/' on the first page
.search ? The query string followed
.hash Part starting from
#.href Full URL

The difference between host and hostname

In the above example, you may notice that host and hostnameReturn 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; // ''

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, while hostname will return only the host name.

How to change URL properties

Not only can we call the location` attribute 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'
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'
The only property that cannot be set is

window.location.origin, which is read-only.

Location object

window.location Returns 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
The reason we do this is that these are global variables in our browser.

Detailed explanation of window.location object in JS (cheat sheet)

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
}
I think most developers know that

window is a global variable. That way it's less likely to cause confusion. To be honest, I didn't know location## until I wrote this article # is a global variable. It is recommended that you use window.location instead of other writing methods.

window.location method

Method##.assign()Load a new Document.replace()Replace the current document with a new one.reload()Reload the current page.reload()Returned 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

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

Replace

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

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

如何让页面重定向

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

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

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

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

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

myUrlUpdateFunction();

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

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

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

作者:Samantha Ming

译者:前端小智

更多编程相关知识,请访问:编程入门!!

Function

The above is the detailed content of Detailed explanation of window.location object in JS (cheat sheet). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

20+道必知必会的Vue面试题(附答案解析)20+道必知必会的Vue面试题(附答案解析)Apr 06, 2021 am 09:41 AM

本篇文章整理了20+Vue面试题分享给大家,同时附上答案解析。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),