1

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!

colinified101
  • 39
  • 1
  • 3
  • `popstate` won't fire in that scenario as the navigation is performed via pushState, this is the correct behavior. I don't think it's a good idea messing with the site's internal history states. See [this answer](https://stackoverflow.com/a/34100952) for a simple example of patching appearance of youtube pages. – wOxxOm Dec 23 '20 at 09:13

1 Answers1

0

I had a similar issue, I wrapped up my entire contentScript functionality into a function called main().

Then added a custom eventListener called yt-navigate-finish and called main() every time this event was triggered.

This way I could satisfy my need of executing contentScript everytime a new page is loaded or navigated on YouTube

document.addEventListener("yt-navigate-finish", function(event) {
    console.log("Content changed")
    main()
});

Answer referenced and modified form https://stackoverflow.com/a/45956628/6123830

Nithin S
  • 88
  • 2
  • 7