0

I am bypassing the data worked in offscreen.js to content-script.js using sendResponse in background.js, but a problem arose where the callback function of chrome.runtime.sendMessage in content-script.js does not work.

below is background.js

const OFFSCREEN_DOCUMENT_PATH = 'offscreen.html';

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  const { msg, results, status } = request;

  handleHasDocument().then(async (hasDocument) => {
    console.log('hasDocument: ', hasDocument);
    if (!hasDocument) {
      await chrome.offscreen.createDocument({
        url: OFFSCREEN_DOCUMENT_PATH,
        reasons: [chrome.offscreen.Reason.DOM_PARSER],
        justification: 'Parse DOM',
      });

      chrome.runtime.sendMessage(msg);
    } else {
      console.log(results);
      // part passing the data worked in offscreen.js to content-script.js using sendResponse
      sendResponse({
        status,
        body: results,
      });

      await chrome.offscreen.closeDocument();
    }
  });

  return true;
});

async function handleHasDocument() {
  const matchedClients = await clients.matchAll();
  for (const client of matchedClients) {
    if (client.url.endsWith(OFFSCREEN_DOCUMENT_PATH)) {
      return true;
    }
  }
  return false;
}

and offscreen.js

const type = 'offscreen';

chrome.runtime.onMessage.addListener(handleMessages);

async function handleMessages(msg) {
  fetch(`https://example.com?q=${msg}`).then((res) => {
    const { status } = res;

    if (status === 200) {
      res.text().then((text) => {
        ...
        chrome.runtime.sendMessage({
            results: [],
            type: 'type',
            status,
          });
        }
      });
    } else {
      chrome.runtime.sendMessage({
        type: 'type',
        status,
      });
    }
  });
}

and finally is my content-script.js

const reqMessage = (e) => {
  const msg = window.getSelection().toString();

  if (!msg.trim() || !chrome.runtime) return;

  chrome.runtime.sendMessage({ msg }, (res) => {
    // It doesn't work from below
    console.log(res);
    ...
  });
};

document.onkeydown = (e) => {
  e.metaKey && e.ctrlKey && reqMessage(e);
};
};

Nothing error log both of content-script.js and background.js

What is wrong in my code?

reference my full code: https://github.com/withbbang/new-chrome-extension

Bread Kim
  • 21
  • 2

0 Answers0