Detect changes on the url
There is no "clean", event-based way to detect such URL changes from a content script.
They are done with history.pushState
API - and using that API doesn't emit any DOM event.
Two possible indirect event-based approaches, besides the already mentioned poll-based one:
An extension can override
history.pushState
with an injected script to additionally emit a DOM event that can be listened to in a content script.This approach is described in detail here.
The downside is that, depending on the code of the page in question, the injected script may need to be injected early, needing
run_at: document_start
which is suboptimal for page load performance.Use a background page that listens to
chrome.webNavigation.onHistoryStateUpdated
event.If you need to detect this in a background page — perfect, you're done, without ever needing a content script.
If you need to detect this in a content script, you can use
details.tabId
in the event listener to send a message to the right content script.
You need to store the URL when the page loads as a starting point and setInterval
to check for changes and modify based on that.
The following code does this check twice a second (500ms):
// store url on load
let currentPage = location.href;
// listen for changes
setInterval(function()
{
if (currentPage != location.href)
{
// page has changed, set new page as 'current'
currentPage = location.href;
// do your thing..
}
}, 500);