Search code examples
javascriptgoogle-chrome-extension

Adding a listener to webNavigation, in a chrome extension's background script everytime a url matching a pattern is visited


I am trying to add a listener in the background.js file of a chrome extension. I want this listener to ideally be filtered only for url's matching, for example, netflix.com/watch/

First, I tried chrome.webNavigation.onCompleted.addListener (link), supplying an appropriate filter for the desired netflix URL. However, I've observed that this listener doesn't fire if the URL is navigated to via the browser's forward or backwards buttons. Also, it doesn't seem like the listener fires if the navigation originates from clicking a link on a webpage from the same domain (ie: clicking on a Netflix video while browsing or searching (taking you from netflix.com/browse to the targeted netflix.com/watch URL)).

I then tried chrome.tabs.onUpdated (link). This event fires with the backward/forward buttons, and also fires when navigating from a page of the same domain, but, it doesn't fire when refreshing the same page (since the tab doesn't change in this case). Preferably I would like to handle the refresh case as well.

I could use both listeners to cover each listener's omissions, but there are cases where both will fire at the same time, which isn't desirable.

Is there an event I can listen for that will cover all the situations I described?


Solution

  • chrome.tabs.onUpdated is actually fired when refreshing a tab so your code is incorrect. I guess it looks for changeInfo.url which is not provided on refresh.

    Look at status as well and use url or pendingUrl from the tab parameter:

    chrome.tabs.onUpdated.addListener((tabId, info, tab) => {
      if (info.url || info.status === 'loading') {
        const url = info.url || tab.pendingUrl || tab.url;
        console.log(url); // prints in the *background* console
      }
    });
    

    For webNavigation with SPA (Single-Page Application) sites like netflix/youtube you need to listen to more events: onHistoryStateUpdated, onReferenceFragmentUpdated.