0

I'm learning Chrome extension development and want to update the content of my popup whenever theres change to the URL (Not a tab change!).

My content script is basically accessing the DOM and grabs some text to set as a name within Chrome localStorage. popup.js then retrieves the name from localStorage and outputs within the pop.up.

Problem: How can I re-run the content script whenever the current pages URL changes? I think I would need to use chrome.tabs.onUpdated.addListener but unsure of how to implement. How can I best implement this functionality?

So far I have the following:

contentScript.js

// Store name in localStorage
chrome.storage.local.set({ name });

popup.js

// Get name from localStorage and set as some state
useEffect(() => {
    chrome.storage.local.get('name', (data) => {
        setName(data.name);
    });
}, []);

manifest.json

"permissions": ["storage", "tabs"],
"content_scripts": [
    {
        "matches": ["https://site.storm.com/*"],
        "js": ["contentScript.js"]
    }
Samuel
  • 5,529
  • 5
  • 25
  • 39
  • "chrome.tabs.onUpdated.addListener" that must be use in the "background.js" not in the contentScript.js file. – user1731468 Apr 11 '22 at 21:31
  • And check the MDN doc for an example code https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/tabs/onUpdated#examples – user1731468 Apr 11 '22 at 21:33
  • You can use chrome.tabs.onUpdated in the popup or the background script as shown in tons of examples, then in its listener [send a message](https://developer.chrome.com/extensions/messaging) to the tab's content script. It's unclear what the problem is. – wOxxOm Apr 12 '22 at 06:58
  • @wOxxOm are you referring to `chrome.runtime.sendMessage()`? So I have included `chrome.tabs.onUpdated.addListener()` in my `popup.js`. I then included `chrome.tabs.sendMessage()` within the onUpdated listener. Now within my contentScript I have `chrome.runtime.onMessage.addListener()` but not receiving any messages. The concepts are not clicking yet but would appreciate further advice! – Samuel Apr 12 '22 at 14:15
  • If you reload the extension, the content script won't run automatically. It runs only when the tab [re]loads, see [Chrome extension content script re-injection after upgrade or install](https://stackoverflow.com/q/10994324) – wOxxOm Apr 12 '22 at 14:39
  • I see, so I'm going to have to programmatically inject it – Samuel Apr 12 '22 at 21:34

0 Answers0