Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

javascript - 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?

question from:https://stackoverflow.com/questions/65876608/adding-a-listener-to-webnavigation-in-a-chrome-extensions-background-script-ev

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...