Implementation of front-end routing (3) - History's pushState and replaceState usage

API provided pushStateby  history in HTML5 . replaceState这两个They provide methods for manipulating the browser's history stack .

pushState能够在不加载页面的情况下改变浏览器的URL。这个方法接受三个参数:

The state object , the title of the new state and an optional relative URL.

 history.pushState(data, null, '#/page=1');
    pushState接收3个参数,第一个参数为一个obj,表示浏览器的state属性;
    第二个参数是document.title的值,一般设定为`null`; 第三个参数string,用以改变当前url

 

pushStateThe method pushes a new history record onto the browser history stack at the same time as the changeurl .

The received urlparameter is the stringtype, which is used to change the url of the current address bar. It should be noted that this parameter cannot be cross-domain, that is, the protocol, domain name, and port must be the same. If there is a cross-domain situation, it will prompt:

Example:

in replaceState:

  replaceStateThe received parameters are the pushStatesame, but the final effect is: the address bar url will change according to the received parameters, but the browser does not add the browser's history to the current browsing history stack, but replaces the current browser's history.

Through pushStateand replaceStatecan change the URL, but will not actively trigger the browser reload.

windowObjects also provide  popstatemethods :

This method is used to monitor the browser to switch between different history records and trigger the corresponding events .

goThere is also a  method on the history object provided by the browser backto simulate the user clicking the forward and back buttons of the browser. In a web application, for example, when a <a>label is clicked, a page jump occurs. At this time, after calling history.back()the method, the page rolls back , and the page refreshes at the same time, and window.onpopstatethis event cannot be monitored at this time. But if the URL is changed by pushStateor and no browser refresh occurs , then use or , so the event will be fired .replaceStatehistory.back()history.go()popstate

 

 

The output is as follows:

Note: By pushStateadding content to the url that ?page=1can be obtained by location.searchgoing to search. However, if you location.searchchange urlit, it will actively trigger the browser reload.

The API has a general understanding, so where can these methods be used? A common scenario is that in a single-page application, the front-end routing design is completed through these APIs, pushStateand  the browser  replaceStatecan be changed without refreshing at the same time through these APIs, and a series of asynchronous actions can be completed by monitoring the browser history.urlpopstate 

A simple route is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style>
    a {color: red;text-decoration: underline;}
  </style>
</head>
<body>
  <a data-href="/post">post</a>
  <a data-href="/login">login</a>
  <script>
       const Router = [];
       const addRoute = (path ='', handle=() =>{}) => {
        let obj = {
          path,
          handle
        };
        Router.push(obj);
       }
       // Add route definition 
       addRoute('/post', function (){
         // todo... 
          alert('/post' );
       })
       addRoute('/login', function(){
        // todo...
         alert('login');
       })
       // Route handling 
       const routeHandle = (path) => {
         for ( var item of Router){
           if (item.path === path) {
            item.handle.apply(null, [path]);
            return true;
          }
        }
       }
       document.addEventListener('click', function(e) {
        let dataset = e.target.dataset;
        if(dataset) {
            if(routeHandle(dataset.href)) {
                var url = window.location.href;
                history.pushState({route: dataset.href}, null , oriUrl + dataset.href);
                 // prevent default behavior 
                return  false ;
                 // e.preventDefault(); 
            }
        }
    })
  </script>
</body>
</html>

 

The general idea of ​​implementation is to <a>add routing information , then intercept <a>the default behavior of the label and match it with the registered routing information . If the match is successful , the corresponding method is called .handle

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324861318&siteId=291194637