I am trying to detect for the history.popState() event when navigating through YouTube. Here is my code, all of which are in my content script:
if (window.location.href == 'https://www.youtube.com/') {
history.pushState({id: 0}, '',);
chrome.runtime.sendMessage({message: 'home'});
}
window.addEventListener('yt-navigate-start', function() {
if (window.location.href.includes('/results')) {
history.replaceState({id: 1}, '');
chrome.runtime.sendMessage({message: 'results'});
} else if ('/watch' === location.pathname) {
history.replaceState({id: 2}, '');
chrome.runtime.sendMessage({message: 'watch'});
}
});
window.addEventListener('popstate', function (event) {
setTimeout(idChange, 2000);
}, false);
if (history.state && history.state.id === 1) {
console.log('id1')
} else if (history.state && history.state.id === 2) {
console.log('id2');
} else if (history.state && history.state.id === 0) {
console.log('id0');
}
I can register the popstate event event when navigating from youtube home to the results, then pressing back button. But when I go from youtube home to results then to a specific video and click back to return to results, the pop state event doesn't fire. Am I doing something wrong?
Thank you!