bom的总结3:history对象

作者: 我不是大熊 | 来源:发表于2018-01-14 04:40 被阅读0次

    history对象

    history对象保存着用户的上网记录,使用go()方法可以在上网记录中前进后退:

    1.基本操作
    history.go(0);//刷新
        history.go(1);//前进
        history.forward();//同上
        history.go(-1);//后退
        history.back();//同上
        history.go('http://baidu.com');//跳转到最近的http://baidu.com页面,不定是前进还是后退,取最近
    
    2. history.pushState
        //检测是否支持history
        if(!!(window.history && history.pushState)){
            console.log('支持history api');
        }else{
            console.log('不支持history api');
        }
        //pushState方法3个参数:①state:状态对象,会传入popstate的回调函数中;②title:标题,目前浏览器都忽略,可忽略,③url:地址栏将显示的地址,不能跨域
        var stateObj = { foo: 'bar' };
        history.pushState(stateObj, 'page 2', '2.html');
        //总之,pushState方法不会触发页面刷新,只是导致history对象发生变化,地址栏会有反应
    
    3.history.replaceState
        //replaceState的参数和pushState一样,区别是它修改浏览历史中当前纪录,而不是添加
        history.replaceState({page:1},"page1","page1.html");
    
    4.history.state属性
        console.log(history.state);//如果没有,将返回null
    
    5.popstate事件
        //每当同一个文档的浏览历史(即history对象)出现变化(只有当前进、后退的时候才会,比如用户点击前进后退按钮,比如js调用go(-1)/back()/forward时,就会触发popstate事件。
        window.onpopstate = function (event) {
            console.log('location: ' + document.location);
            var state = JSON.parse(JSON.stringify(event.state));
        };
        history.pushState({page:3},"page3","#");
        history.back();
    
    6.URLSearchParams API

    因为兼容性问题,暂时先不讨论这个,在location当中已经实现过怎样获取查询字符串参数了。

    相关文章

      网友评论

        本文标题:bom的总结3:history对象

        本文链接:https://www.haomeiwen.com/subject/ywnhoxtx.html