xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

history API 改写 & pushState Event All In One

history API 改写 & pushState Event All In One

应用场景: 前端监控

改写 method

// history API 改写
    _rewriteHistory (type) {
        const origin = window.history[type];
        return function () {
            const rs = origin.apply(this, arguments);
            const e = new Event(type.toLocaleLowerCase());
            e.arguments = arguments;
            window.dispatchEvent(e);
            return rs;
        };
    }

    /**
     * @description
     * @author eric
     * @param {function} cb
     * @param cb options = {ua, beginTime, endTime, oldUrl, newUrl, newStartTime}
     */
    changeRouter (cb) {
        window.history.pushState = this._rewriteHistory('pushState');
        window.history.replaceState = this._rewriteHistory('replaceState');
        // ✅ popstate
        window.addEventListener('popstate', () => {
            this._emit(cb, '浏览器的前进后退 popstate');
        });
        // ❌ pushstate ❓
        window.addEventListener('pushstate', () => {
            this._emit(cb, '单页路由变化 pushstate');
        });
        // ❌ replacestate ❓
        window.addEventListener('replacestate', () => {
            this._emit(cb, '单页路由替换 replacestate');
        });
        // ✅ hashchange
        window.addEventListener('hashchange',(e) => {
            // console.log('hashchange event', e);
            let timeDiff = this._getTimestamp() - this.beginTimestamp;
            this.beginTimestamp = this._getTimestamp();
            console.log(`hashchange 待了时长: ${timeDiff}`);
            this._emit(cb, '单页路由 hashchange');
        });
    }

事件

hashchange event

https://developer.mozilla.org/en-US/docs/Web/API/Window/hashchange_event

popstate event

https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate

History API

https://developer.mozilla.org/en-US/docs/Web/API/History_API

window.addEventListener('popstate', (event) => {
  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
});

history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null"
history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}"

window.onpopstate = function(event) {
  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
};
history.pushState({page: 1}, "title 1", "?page=1");
history.pushState({page: 2}, "title 2", "?page=2");
history.replaceState({page: 3}, "title 3", "?page=3");
history.back(); // Logs "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back(); // Logs "location: http://example.com/example.html, state: null"
history.go(2);  // Logs "location: http://example.com/example.html?page=3, state: {"page":3}"

方法

https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

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

https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState

history.replaceState(state, title, [url])

go



back



forward



属性

https://developer.mozilla.org/en-US/docs/Web/API/History/state

const currentState = history.state

https://developer.mozilla.org/en-US/docs/Web/API/History/length

const length = history.length

scrollRestoration

滚动恢复

https://developer.mozilla.org/en-US/docs/Web/API/History/scrollRestoration

const scrollRestore = history.scrollRestoration

pushstate ❌, 不存在的 event


window.onpushstate = function (event) {
  if (event.state) {
    // history changed because of pushState/replaceState
  } else {
    // history changed because of a page load
  }
}

window.addEventListener('pushstate', (event) => {
  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
});

popstate ✅

window.onpopstate = function (event) {
  if (event.state) {
    // history changed because of pushState/replaceState
  } else {
    // history changed because of a page load
  }
}


window.addEventListener('popstate', (event) => {
  console.log("location: " + document.location + ", state: " + JSON.stringify(event.state));
});



(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!

refs



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-02-23 11:34  xgqfrms  阅读(76)  评论(7编辑  收藏  举报