Quick actions

cmd+k|ctrl+k

Navigation

Languages

detect change url

Snippet info

Language

JavaScript

Visibility

public

Author

cheshirysh

Created

2017-11-02T15:40:57Z

Updated

2017-11-02T15:40:57Z

    function listenForURLChange(cb) {
        let body = document.getElementsByTagName("body")[0];

        document.addEventListener('onurlchange', (e) => {
            cb(e.detail.path);
        });

        let html = `
        let pushState = window.history.pushState;
        window.history.pushState = function(state) {
            document.dispatchEvent(new CustomEvent('onurlchange', { detail: state }));
            return pushState.apply(window.history, arguments);
        };`;

        let patch = document.createElement("script");
        patch.type = 'text/javascript';
        patch.innerHTML = html;
        body.appendChild(patch);

        // Also we'll catch "back" button.
        window.onpopstate = (e) => { cb(e.state.path) };
    }
INFO