通过history.pushState无刷新改变url 背景 表现 使用 实例

通过history.pushState无刷新改变url
背景
表现
使用
实例

通过history.pushState无刷新改变url

在浏览器中改变地址栏url,将会触发页面资源的重新加载,这使得我们可以在不同的页面间进行跳转,得以浏览不同的内容。但随着单页应用的增多,越来越多的网站采用ajax来加载资源。因为异步加载的特性,地址栏上的资源路径没有被改变,随之而来的问题就是页面的状态无法被保存。这导致我们难以通过熟悉的方式(点击浏览器前进/后退按钮),在前后的页面状态间进行切换。 为了解决ajax页面状态不能返回的问题,人们想出了一些曲线救国的方法,比如利用浏览器hash的特性,将新的资源路径伪装成锚点,通过onhashchange事件来改变状态,同时又避免了浏览器刷新。但这样始终显得有些hack。 现在HTML5规范为 window.history引入了两个新api,pushStatereplaceState,我们可以使用它很方便的达到改变url不重载页面的目的。


表现

改变地址栏url,不刷新页面。 通过history.pushState无刷新改变url
背景
表现
使用
实例 观察地址栏,可以看到当url路径由”join”改变为”login”时,页面状态也随之改变,但并没有造成背景图片等资源的重新加载。 此时”join”被压入历史栈,当点击浏览器后退按钮时仍然能够回到”join”状态。


使用

pushStatereplaceState方法类似,都有改变当前地址栏URL的作用。主要区别在于pushState会在浏览器中创建一条新的历史纪录,而replaceState仅仅替换将当前地址为指定URL。 下面以pushState接口为例:

API

history.pushState(state, title[, url]);

事件

执行history.back()history.forward()后触发  window.onpopstate事件

参数

state: 对象,可以存存放一些数据表示当前状态。当浏览器执行前进后退操作时触发onpopstate事件,state将成为event的子对象,可通过event.state获取先前状态。但是注意state中的属性值不能为引用类型对象,会报ObjectCloneError(对象克隆异常),例如允许{data:”test”},不允许{data:document.querySelector(‘#testId’)}。 title:目前无特殊意义,一般可以传入 document.title 或 ”(空字符串)。 url:要替换的url,如果是pushState则会添加一条历史记录,不允许跨域。

示例

history.pushState({title:"login"}, "login", "fish/login");
window.addEventListener("popstate", function(event){
    if(event.state) {
        var state = event.state.title;
        switch(state) {
           case "login":.............;break;
           case "join" :.............;break;
           case "home" :.............;break;
        }
     }
}, false);

实例

下面以一个具体实例来展示pushState的作用,注意地址栏的变化。

效果

通过history.pushState无刷新改变url
背景
表现
使用
实例

两次点击白色圆环改变页面背景,将在当前浏览器历史会话(window.history)中写入两条新记录:“/pushState.html?state=blue”和“/pushState.html?state=org”。 点击浏览器后退/前进按钮相当于执行history.back()history.forward()方法,将触发onpopstate事件,通过监听onpopstate事件改变相应状态。

源代码

本实例在Chrome下编写调试,请在Chrome、Firefox、IE10+等现代浏览器中运行。

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<meta name="renderer" content="webkit" />
<head>
<title>pushState demo</title>
<style>
    body {
        font-family: "Microsoft YaHei"; 
        transition: background-color .3s;
    }
    .bg-org {
        color: #383c3c;
        background-color: #FF6633;
    }
    .bg-blue {
        color: #fbfaf5;
        background-color: #6699FF;
    }
    .time {
        margin-top: 20%;
        text-align: center;
        font-size: 4em;
        font-weight: 100;
    }
    .switch {
        margin: auto;
         30px;
        height: 30px;
        position:absolute;
        bottom:25%;
        left:0;
        right:0;
        cursor:pointer;
        box-shadow: 0 0 0 5px rgba(255,255,255,.6);
        border-radius: 50%;
        transition: box-shadow .1s;
    }
    .switch:hover {
        box-shadow: 0 0 0 5px rgba(255,255,255,.75);
    }
    .switch:active {
        box-shadow: 0 0 0 30px rgba(255,255,255,.4);
    }
</style>
</head>

<body class="bg-org">
    <h1 id="time" class="time">Loading...</h1>
    <div id="switch" class="switch"></div>
    <script>
        var time = $('#time');
        function $(selector) {return document.querySelector(selector);}

        // 显示当前时间
        setInterval(function(){
            var date = new Date(),
                format = function(n) {return n<10?'0'+n:n};
            time.innerHTML = format(date.getHours()) + ' : ' + format(date.getMinutes()) + ' : ' + format(date.getSeconds()); 
        }, 500);

        $('#switch').addEventListener('click', toggleState, false);

        // 监听popstate事件
        history.pushState && window.addEventListener("popstate", function(e) {

            // 获取history.state对象中的状态信息
            // 在这里state将自动成为event的子对象,可直接通过event.state访问
            var flag = e.state && e.state.title;
            $('body').className = flag || ($('body').className=='bg-org'?'bg-blue':'bg-org');
        }, false);
        function toggleState(e) {
            var flag = $('body').className=='bg-org'?'bg-blue':'bg-org';

            // 新建历史记录,将当前状态信息保存至history.state中
            history.pushState && history.pushState({ title: flag }, flag, 'pushState.html?state='+flag.split('-')[1]);
            $('body').className = flag;
        }
    </