navigationdom-eventssveltekitcontent-scriptbrowser-extension

Listen to SvelteKit navigation from browser extension content script


Having browser extensions that run on page load is pretty straight forward to setup in content scripts for classic MPAs.

However, for hybrid approaches like SveleKit which handles navigation in the SPA style after initial SSR, I am still trying to figure out the best way to execute an external browser extension content script on each navigation.

Since the URL clearly changes on navigation - without reload - I guess it should be possible to listen to connected window events.

I've tried to listen to popstate but wasn't able to see any output for such a listener:

window.addEventListener('popstate', function (event) {
    console.debug(event.state)
})

Solution

  • Instead of using the older history API and its popstate and hashchange events, using the new navigation API listening for the navigation event solves this wonderfully:

    navigation.addEventListener('navigate', (navigationEvent) => {
      // check on the event if we really want to run custom logic here
      // end then run our custom logic
    })
    

    Credits to @wOxxOm pointing it out.