I have a very simple component to demonstrate this issue.
HTML:
<template>
<button onclick={push1}>Push 1</button>
<button onclick={push2}>Push 2</button>
<button onclick={push3}>Push 3</button>
</template>
JavaScript:
import { LightningElement } from 'lwc';
export default class Users extends LightningElement {
connectedCallback() {
window.addEventListener('popstate',this.handlePopstate);
}
handlePopstate = (event) => {
console.log('handling popstate');
}
push1() {
this.push(1);
}
push2() {
this.push(2);
}
push3() {
this.push(3);
}
push (value) {
console.log('pushing new history');
const params = new URLSearchParams(window.location.search);
params.set('c__push',value);
const newUrl = `${window.location.origin}${window.location.pathname}?${params}`;
window.history.pushState({ path: newUrl, push: value },'',newUrl);
}
}
The pushState function itself is working exactly as expected. However, the back and forward buttons do not navigate through the updated history stack as expected. Here is an example I've simulated:
- Click "Push 1" => updates c__push param to 1
- Click "Push 2" => updates c__push param to 2
- Click "Push 3" => updates c__push param to 3
- Click back on browser => updates c__push param to 2, but the forward button is disabled after VERY briefly showing as enabled.
- Click back on browser again => c__push param stays at 2, and forward button becomes enabled, but if click will keep param at 2. <- this whole step seems to behave as though a second instance of this history somehow made it into the stack
- Click back on browser again => c__push param goes to 1, and forward button is disabled again.
I can't find anything to suggest that window.history.pushState shouldn't work in LWC. Does anyone have any idea what might be at play here?
If pushState() really is broken in LWC then I'm not sure how I'm going to build a reasonable navigational structure. It seems pushState() SHOULD work in LWC though, right...? It seems at least one other person in the world is or at least was doing this, though I'm not sure what the responder in this thread is referring to with "SecureWindow" as this doesn't seem to be something I can declare: Lightning LockerService & History.pushState