Use JS to intercept pushState and replaceState events and pushstate events

Source: Internet
Author: User

Use JS to intercept pushState and replaceState events and pushstate events

History. pushState and history. replaceState can change the URL without refreshing the current page, but the content of the new page obtained through AJAX cannot be obtained.
Although various HTML5 documents say that the window. onpopstate event can intercept pushState messages, in actual tests, onpopstate has no function at all and cannot intercept pushState messages.

The code for correctly obtaining the pushState event was found after Google review.
Https://stackoverflow.com/a/25673911

 

// Add this: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');// Use it like this:window.addEventListener('pushState', function(e) {    console.warn('THEY DID IT AGAIN!');});window.addEventListener('replaceState', function(e) {    console.warn('THEY DID IT AGAIN!');});

 

This code overwrites the original function in history and then activates an event on its own.
This will solve the problem that pushState cannot activate the event.
Remember to put this code before loading the document.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.