Polymer / pwa-helpers

Small helper methods or mixins to help you build web apps.
BSD 3-Clause "New" or "Revised" License
439 stars 48 forks source link

Router doesn't monitor pushState/replaceState #54

Open ernsheong opened 5 years ago

ernsheong commented 5 years ago

If URL changes due to pushState/replaceState, installRouter does not capture it.

ernsheong commented 5 years ago

Ain't pretty, but here's how one library does it:

// we must hijack pushState and replaceState because we need to
// detect when consumer attempts to use and trigger a page load
this.historyChangeStates = [window.history.pushState, window.history.replaceState];
this.historyChangeStates.forEach((method) => {
    window.history[method.name] = (...args) => {
        const [state] = args;
        method.apply(history, args);
        this.changedUrl(state);
    };
});

https://github.com/mkay581/router-component/blob/master/src/router-component.ts#L47

mwilc0x commented 5 years ago

I just ran into this too, noticing that when my app updates the route via pushState, the callback from installRouter is not called.

keanulee commented 5 years ago

Our router doesn't monitor pushState/replaceState - we only watch link clicks and back/forward. The idea is that if you call those functions, you can also manipulate your state in script (typically calling the same callback you give installRouter()).

mwilc0x commented 5 years ago

Ok, thank you @keanulee !

mercmobily commented 4 years ago

Probably a little late, but in my code I normally just emit popstate:

const e = new PopStateEvent('popstate', { state: { } })
window.dispatchEvent(e)

As a bonus, I can use the state to pass parameters:

 const e = new PopStateEvent('popstate', { state: { artificial: true, noHistory: noHistory } })
 window.dispatchEvent(e)

Is this not recommended?