为了账号安全,请及时绑定邮箱和手机立即绑定

js中为何直接监听pushState事件无效?

js中为何直接监听pushState事件无效?

慕运维8079593 2019-02-13 17:15:19
chrome 63,直接监听pushState事件无效:window.addEventListener("pushState", function () {        // code    });直接监听replaceState也是无效的,popstate有效。我搜索之后在jb51上找到了一个办法,先添加一段代码,再添加监听就可以了。var _wr = function(type) {  var orig = history[type];  return function() {    var rv = orig.apply(this, arguments);    var e = new Event(type);    e.arguments = arguments;    window.dispatchEvent(e);    return rv;  };};history.pushState = _wr('pushState');history.replaceState = _wr('replaceState');那么为什么直接监听无效呢?是浏览器的问题还是什么原因?测试网址:pixiv 特辑(需要科学上网),从这个页面进入子页面用的就是pushState。
查看完整描述

1 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

没有onpushstate这个事件,当然无法监听到了。


可以把history劫持一下:


(function(history){

    var pushState = history.pushState;

    history.pushState = function(state) {

        if (typeof history.onpushstate == "function") {

            history.onpushstate({state: state});

        }

        // ... whatever else you want to do

        // maybe call onhashchange e.handler

        return pushState.apply(history, arguments);

    };

})(window.history);

history.onpushstate = function(e) {

    console.log('pushed');

}

效果:

https://img1.sycdn.imooc.com//5c8a121d00011e6704290448.jpg

查看完整回答
反对 回复 2019-03-14
  • 1 回答
  • 0 关注
  • 1960 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号