Home >Web Front-end >JS Tutorial >How to Establish Communication from Background Script to Injected Script through Content Script?

How to Establish Communication from Background Script to Injected Script through Content Script?

DDD
DDDOriginal
2024-10-18 11:06:03432browse

How to Establish Communication from Background Script to Injected Script through Content Script?

Sending Message from a Background Script to a Content Script, and Then to an Injected Script

Problem:
Despite attempting to send messages from the background page to a content script and then to an injected script, the process has failed to work as intended. The content script is unable to receive messages from the background script.

Solution:
The issue arises from the manner in which content scripts are injected. When an extension is loaded, it does not automatically inject content scripts into existing tabs. Injection only occurs when a new tab is created or an existing tab is navigated after the extension is loaded.

Solution 1: Conditional Script Injection
To ensure communication between the background and content scripts, a conditional script injection can be employed. The background script can check if the tab is ready to receive messages and inject the content script only if it's not already injected.

Code:

<code class="javascript">// Background script
function ensureSendMessage(tabId, message, callback) {
  chrome.tabs.sendMessage(tabId, { ping: true }, function (response) {
    if (response && response.pong) { // Content script ready
      chrome.tabs.sendMessage(tabId, message, callback);
    } else { // No listener on the other end
      chrome.tabs.executeScript(tabId, { file: "content_script.js" }, function () {
        if (chrome.runtime.lastError) {
          console.error(chrome.runtime.lastError);
          throw Error("Unable to inject script into tab " + tabId);
        }
        // OK, now it's injected and ready
        chrome.tabs.sendMessage(tabId, message, callback);
      });
    }
  });
}</code>

Content script:

<code class="javascript">chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.ping) {
    sendResponse({ pong: true });
    return;
  }
  // Content script action
});</code>

Solution 2: Double Execution Prevention
Another solution involves injecting the content script into the tab but implementing measures to prevent its execution more than once.

Code:

<code class="javascript">// Background script
function ensureSendMessage(tabId, message, callback) {
  chrome.tabs.executeScript(tabId, { file: "content_script.js" }, function () {
    if (chrome.runtime.lastError) {
      console.error(chrome.runtime.lastError);
      throw Error("Unable to inject script into tab " + tabId);
    }
    // OK, now it's injected and ready
    chrome.tabs.sendMessage(tabId, message, callback);
  });
}</code>

Content script:

<code class="javascript">var injected;

if (!injected) {
  injected = true;
  // Your toplevel code
}</code>

Solution 3: Indiscriminate Script Injection
Lastly, you can choose to inject the content script into all tabs upon extension initialization. This is only advisable if your script doesn't interfere with itself when executed multiple times or after the page has loaded.

Code:

<code class="javascript">chrome.tabs.query({}, function (tabs) {
  for (var i in tabs) {
    // Filter by URL if needed
    chrome.tabs.executeScript(tabs[i].id, { file: "content_script.js" }, function () {
      // Now you can use normal messaging
    });
  }
});</code>

Once any of these solutions are implemented, messages can be successfully relayed from the background script to the content script, and eventually to the injected script.

The above is the detailed content of How to Establish Communication from Background Script to Injected Script through Content Script?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn