Getting Chrome Extension content script to recognize delayed change in URL hash

243 views Asked by At

I have a Chrome Extension (currently manifest v2, but will soon upgrade to v3) that needs to work with a SPA that simulates page changes by changing the hash in the URL.

Example:

Page 1: https://www.example.com/somedir/#page1
Page 2: https://www.example.com/somedir/#page2

I have separate content scripts for #page1 and #page2, and a default content script for other pages on the site.

The problem I'm having is that the page initially loads without a hash, and then after a few seconds of delay, the application adds the #page1 hash. In other words, when the user navigates to #page1:

  • The site initially loads as https://www.example.com/somedir/
  • My Chrome Extension content script for #page1, which looks for the include glob *#page1, does not see the #page1 hash in the URL and falls back to the default content script
  • After a few seconds of delay, the site appends the #page1 hash to the URL, presumably by setting location.hash (i.e., the URL is now https://www.example.com/somedir/#page1)

I think what I'm looking for is some way to detect that the #page1 hash has been added to the URL, and then force the extension to re-execute and inject the correct content scripts for #page1. Is there a way to do that? If not, is there some other method to workaround this timing issue?

Thank you.

0

There are 0 answers