Search code examples
javascriptgoogle-chrome-extensiondom-eventstrello

Check browser back in Chrome extension in Trello


I'm developing a Chrome extension, that processes cards in Trello in My Cards list.

Even though Trello is a dynamic JS app, my extension is able to detect URL change when user clicks a link.

BUT how to detect when user clicks a Back/Forward button in browser?

I tried many (easy) ways to detect the Back button I found on the internet, but with no luck. Here's my current detection function.

function detectHistoryChange(handler) {
    document.head.appendChild(document.createElement('script')).text = '(' +
        function () {
            // injected DOM script is not a content script anymore,
            // it can modify objects and functions of the page
            var _pushState = history.pushState;
            history.pushState = function (state, title, url) {
                _pushState.call(this, state, title, url);
                window.dispatchEvent(new CustomEvent('state-changed', { detail: state }));
            };
            // repeat the above for replaceState too
        } + ')(); $(this).remove();'; // remove the DOM script element

    // And here content script listens to our DOM script custom events
    window.addEventListener('state-changed', function (e) {
        console.log('History state changed', e.detail, location.hash);
        handler();
    });
}

Thanks!


Solution

  • Seems like Trello fires an event single-spa:routing-event on navigation. So I added a listener on this event and it works like a charm!