CHROME -EXTENSIONS: How can I run message passing multiple times?

Viewed 109

I am working on a project which produces a Chrome extension. In a background page I have a function named checkingProcess. This function is executed when a new tab is opened or a tab is updated. (I tried to catch the change of URL here.)

chrome.tabs.onActivated.addListener((activeInfo) => {
  checkingProcess(activeInfo.tabId)
})

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  checkingProcess(tab.id)
})

Then, in the checkingProcess function, I have some functions for the data handling and API calls. Then I tried to receive a message that comes from popup. This message represents that the popup was opened by the user.

 chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.msg === 'popup_opened') {
      sendResponse({
        matches_length: response['matches'].length,
        hostname: host,
      })
    }
    chrome.runtime.lastError
  })

After that, it sends a response to the popup. In the popup, I listen to the message and use the response in the popup.

 useEffect(() => {
    chrome.runtime.sendMessage({ msg: 'popup_opened' }, (res) => {
      setHostname(res['hostname'])
      setMatchesLength(res['matches_length'])
      console.log(res['hostname'], 'burası')
      console.log(res['matches_length'], 'burası')
    })
  }, [])

However, I realize that this message process is only executed once, but I need to run it multiple times to access the data in background simultaneously. How can I do that?

1 Answers

Your message is only sent once because it's currently setup in a React.useEffect with an empty list of dependencies. This means this code will only be run once when your component is mounted. If you want to run it "multiple times" you first need to define what this means? Examples are:

  • Executing sendMessage after a user performs some action, like clicking a button. In that case you don't need useEffect. Instead, wire an event handler to that button and perform the sendMessage there.
  • Executing sendMessage after re-render of your component. Simply remove the empty list of dependencies ([]) from your useEffect method. Note: use this with caution. If you setup your component in a way that it re-renders often, this can quickly turn into a situation where many API calls are made.
  • Executing sendMessage after some state within your component changes. Add this variable to the list of dependencies: [loaded]
  • Executing sendMessage every 10 seconds. You'll want to use setInterval within your useEffect, like this:
useEffect(() => {
  const interval = setInterval(() => {
    chrome.runtime.sendMessage({ msg: 'popup_opened' }, (res) => {
      setHostname(res['hostname'])
      setMatchesLength(res['matches_length'])
      console.log(res['hostname'], 'burası')
      console.log(res['matches_length'], 'burası')
    })
  }, 10000);
  return () => clearInterval(interval);
}, []);
Related