Table of Contents
Detailed explanation of how JavaScript operates URLs (commonly used in single-page applications)
1.document.location
2.location.replace
3.window.onhashchange
4. history.pushState
5.history.replaceState
6.window.onpopstate
Home Web Front-end JS Tutorial Detailed explanation of how JavaScript operates URLs (commonly used in single-page applications)

Detailed explanation of how JavaScript operates URLs (commonly used in single-page applications)

Feb 27, 2017 pm 02:33 PM

Detailed explanation of how JavaScript operates URLs (commonly used in single-page applications)

JavaScript has many methods that can operate browser history, whether it is an ordinary page jump We will often deal with these methods, whether it is redirection or hash value changes in single-page applications. Especially in single-page applications, these methods are almost the core methods of page routing. This article discusses these methods in detail.

1.document.location

Location is one of the most useful BOM objects. It provides information about the document loaded in the current window and also provides some navigation functions. In fact, the location object is both a property of the window object and a property of the document object. In other words, window.location and document.location are the same object. It is recommended that you use document.location to adapt to non-browser document environments.
Except for the href attribute set for the a tag, the most commonly used jump method must be: window.location.href="xxx"; In fact, the above code actually executes the location.assign method. In short, the writing methods of the following three URL jumps are exactly the same. They will immediately open a new URL and generate a record in the browser's history:

document.location.assign("xxx");document.location="xxx";document.location.href="xxx";
Copy after login
Copy after login

It should be noted that if you pass this If the URL to be redirected is exactly the same as the current URL, the page will be refreshed, but the browser history will not be added.

2.location.replace

The function is almost exactly the same as location.href="xxx";, there is only one difference, location.replace will be in the browser's history Create a record within the record and replace the previous record. For example, when we open the "a.html" page, there are the following two lines of code in the page:

document.location.href="c.html";document.location.replace("b.html");
Copy after login
Copy after login

The browser first jumps to c.html through location.href , and then use location.replace to jump to b.html. At this time, click the browser's back button, and the browser will directly return to a.html, because the history record of c.html has been overwritten by replace.

3.window.onhashchange

We can monitor the hash value change of the browser URL through the following code form:

window.addEventListener("hashchange",function(){
    //do something
},false);//以下代码都会触发hashchange事件
document.location.hash="#a=1";document.location.href="b.html#b=1";document.location.replace("c.html#c=1");
Copy after login
Copy after login

When we cause browsing by rewriting the location When the server URL hash value changes, the hashchange event is triggered. If URL rewriting causes a page refresh (such as changing URL query parameters, or jumping directly to a cross-domain address), the hashchange event will be skipped directly. Please note that changes in the URL hash value may not always trigger the hashchange event. The method introduced below is to change the URL but not trigger the hashchange.

4. history.pushState

The pushState method receives three parameters: an object that records the historical state (this object will be passed in when the popstate event is triggered, and has a size limit of 640K); A string representing the history title; an address with the same origin as the current URL. Typical usage is as follows:

history.pushState({}, "", "b.html");
Copy after login
Copy after login

history.pushState() method will set the URL to a same-origin URL value, and the Referrer header of Ajax requests sent after this will use this The new value also generates a new history record in the browser history. However, the pushState method will not refresh the page, and the change in the URL hash value caused by pushState will not trigger the hashchange event. If pushState sets an address that is exactly the same as the current URL, a new record will still be added to the browser's history.

5.history.replaceState

This method is basically the same as history.pushState. The only difference is that replaceState will be overridden like location.replace Previous history.
More introduction about history.pushState and history.replaceState:
http://www.php.cn/

6.window.onpopstate

We can pass the following Code form to listen to the browser's popstate event:

window.addEventListener("popstate",function(event){
    //do something},false);
Copy after login
Copy after login

Similar to the hashchange event, popstate will trigger when any URL changes (hashchange will only trigger when the hash value changes), and history.pushState and history. replaceState will not trigger the popstate event either. The popstate event will only be triggered when the browser goes back, forward, or rewrites the hash value. If URL rewriting causes a page refresh (such as changing URL query parameters, or jumping directly to a cross-domain address), the popstate event will be skipped directly.
Please note here the parameter "event" passed to the event function in the code. The event parameter contains the state object. This state object is the first state parameter passed in when calling the history.pushState and history.replaceState methods. We can perform certain processing on historical records through this state transfer method.

Detailed explanation of how JavaScript operates URLs (commonly used in single-page applications)

JavaScript has many methods that can operate browser history, whether it is a normal page jump or a single-page application hash value We all deal with these methods frequently, especially in single-page applications. These methods are almost the core methods of page routing. This article discusses these methods in detail.

1.document.location

location是最有用的BOM对象之一,它提供了与当前窗口中加载的文档有关的信息,还提供了一些导航功能。事实上,location对象既是window对象的属性,又是document对象的属性。换句话说,window.location和document.location是同一个对象。这里推荐大家使用document.location的写法,以适应非浏览器文档环境。
除去为a标签设置的href属性,大家最常用的跳转方式一定就是:window.location.href=”xxx”;实际上,上面这句代码真正执行的是location.assign方法。简而言之,下面三中URL跳转的写法完全等同,都会立即打开新的URL并在浏览器的历史记录中生成一条记录:

document.location.assign("xxx");document.location="xxx";document.location.href="xxx";
Copy after login
Copy after login

需要注意的是,如果通过这种方式跳转的URL与当前URL完全相同,则页面会刷新,但是浏览器历史记录不会新增。

2.location.replace

功能几乎与location.href=”xxx”;完全相同,只有一个区别,location.replace会在浏览器的历史记录中生成一条记录,并替换前一条记录。举个例子,当我们打开“a.html”页面,页面内有如下两行代码:

document.location.href="c.html";document.location.replace("b.html");
Copy after login
Copy after login

浏览器先通过location.href的方式跳转到c.html,接着又使用location.replace跳转到b.html。此时点击浏览器的后退按钮,浏览器会直接返回a.html,因为c.html这条历史记录被replace覆盖了。

3.window.onhashchange

我们可以通过如下代码形式来监听浏览器URL的哈希值变化:

window.addEventListener("hashchange",function(){
    //do something
},false);//以下代码都会触发hashchange事件
document.location.hash="#a=1";document.location.href="b.html#b=1";document.location.replace("c.html#c=1");
Copy after login
Copy after login

当我们通过改写location的方式引起浏览器URL哈希值变化时,hashchange事件就会触发。如果URL重写导致了页面刷新(例如改变了URL查询参数,或者直接跳向一个跨域地址),hashchange事件会直接被跳过。请注意,URL哈希值变化不一定总是会触发hashchange事件,下面要介绍的方法就是改动URL但不触发hashchange。

4. history.pushState

pushState方法接收三个参数:一个记录历史状态的对象(该对象会在popstate事件触发时被传入,有640K的大小限制);一个代表历史记录标题的字符串;一个与当前URL同源的地址。典型的使用方式如下:

history.pushState({}, "", "b.html");
Copy after login
Copy after login

history.pushState()方法会将URL设置为一个同源URL值,在此之后发送的Ajax请求的Referrer头部都会使用这个新的值,同时在浏览器历史记录中生成一条新的历史记录。但是pushState方法不会刷新页面,pushState引起的URL哈希值变化也不会触发hashchange事件。pushState如果设置了一条与当前URL完全相同的地址,浏览器的历史记录中仍然会新增一条记录。

5.history.replaceState

该方法与history.pushState基本相同,唯一的区别就是replaceState会像location.replace一样覆盖先前历史记录。
关于history.pushState和history.replaceState的更多介绍:
http://www.php.cn/

6.window.onpopstate

我们可以通过如下代码形式来监听浏览器的popstate事件:

window.addEventListener("popstate",function(event){
    //do something},false);
Copy after login
Copy after login

与hashchange事件类似,popstate会在任何URL变化时触发(hashchange只会在哈希值变化时触发),并且history.pushState和history.replaceState也不会触发popstate事件。只有在浏览器后退、前进、重写哈希值的情况下才会触发popstate事件。如果URL重写导致了页面刷新(例如改变了URL查询参数,或者直接跳向一个跨域地址),popstate事件会直接被跳过。
这里请注意一下代码中传给事件函数的参数“event”,event参数中包含state对象,这个state对象就是在调用history.pushState和history.replaceState方法是传入的第一个状态参数,我们可以通过这种状态传递方式来对历史记录进行一定处理。

 以上就是详解JavaScript操作URL的方法(单页应用常用)的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why NameResolutionError(self.host, self, e) from e and how to solve it Why NameResolutionError(self.host, self, e) from e and how to solve it Mar 01, 2024 pm 01:20 PM

The reason for the error is NameResolutionError(self.host,self,e)frome, which is an exception type in the urllib3 library. The reason for this error is that DNS resolution failed, that is, the host name or IP address attempted to be resolved cannot be found. This may be caused by the entered URL address being incorrect or the DNS server being temporarily unavailable. How to solve this error There may be several ways to solve this error: Check whether the entered URL address is correct and make sure it is accessible Make sure the DNS server is available, you can try using the "ping" command on the command line to test whether the DNS server is available Try accessing the website using the IP address instead of the hostname if behind a proxy

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

What is the difference between html and url What is the difference between html and url Mar 06, 2024 pm 03:06 PM

Differences: 1. Different definitions, url is a uniform resource locator, and html is a hypertext markup language; 2. There can be many urls in an html, but only one html page can exist in a url; 3. html refers to is a web page, and url refers to the website address.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles