0

Belows are my code snipets.

How to sendResponse in place A or B or C?

It seems like sendResponse only work in place D and not in A or B or C because ABC are after async await methods.

// in background.js, add listeners
chrome.runtime.onMessage.addListener(
  async function (request, sender, sendResponse) {
    if (request.type === 'get-text') {
      // sendResponse({abc:'abc'}) // works here. D
      const tab = await getTab();
      // sendResponse({bcd:'bcd'}) // doesn't work here. C
      const data = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        function: () => {
          // get text from dom 
          return text;
        },
        args: []
      }, (bundleData) => {
        // sendResponse({test:'test'}) // doesn't work here. B
      });

      // sendResponse({efg:'efg'}) // doesn't work here. A
    }
}

// in popup.jsx
    useEffect(() => {
 
        const getText = async () => {
            const response = await chrome.runtime.sendMessage({ type:'get-text' })
            console.log(response);
        }
            getText().catch(e=>console.log('error: ', e))
    }, [])

My chrome extension is build on React 18. Using manifest v3

LittleTeemo
  • 184
  • 2
  • 12

1 Answers1

0

To send a response in your chrome extension, you can use the sendResponse function. Although it has some limitations such as it can only be called from within the listener function and that it can only be called once per message, But it can help in basic programs like yours.

// in background.js
if (request.type === 'get-text') {
  const sendResponse = (data) => {
    chrome.runtime.sendMessage({ data });
  };
  const data = await chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: () => {
      // get text from dom 
      return text;
    },
    args: []
  });
  sendResponse(data[0].result);
}

// in popup.jsx
useEffect(() => {
  const getText = async () => {
    const response = await chrome.runtime.sendMessage({ type:'get-text' })
    console.log(response);
  }
  getText().catch(e=>console.log('error: ', e))
}, [])

nischal sharma
  • 479
  • 1
  • 14