Home >Web Front-end >JS Tutorial >How to Send Messages from a Background Script to a Content Script and then to an Injected Script?

How to Send Messages from a Background Script to a Content Script and then to an Injected Script?

Barbara Streisand
Barbara StreisandOriginal
2024-10-18 12:04:26305browse

How to Send Messages from a Background Script to a Content Script and then to an Injected Script?

Sending Message from a Background Script to a Content Script, then to an Injected Script

Problem Statement

The task at hand aims to establish a communication channel between a background script and a content script. The content script is responsible for injecting another script into the webpage, and the injected script is the recipient of the messages. However, this communication is proving unsuccessful, specifically the initial message transmission from the background script to the content script.

Understanding the Issue

The root of the problem lies in the nature of content script injection. Chrome does not automatically inject content scripts into existing tabs when an extension is loaded or reloaded. Instead, injection only occurs upon subsequent tab navigation or opening new tabs that match the specified URL patterns.

Solutions

Solution 1: Ensure Content Script Readiness

<code class="js">// Background
function ensureSendMessage(tabId, message, callback){
  chrome.tabs.sendMessage(tabId, {ping: true}, function(response){
    if(response &amp;&amp; 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); }
        else { chrome.tabs.sendMessage(tabId, message, callback); }
      });
    }
  });
}

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

Solution 2: Always Inject Script with Runtime Check

<code class="js">// Background
function ensureSendMessage(tabId, message, callback){
  chrome.tabs.executeScript(tabId, {file: "content_script.js"}, function(){
    if(chrome.runtime.lastError) { console.error(chrome.runtime.lastError); }
    else { chrome.tabs.sendMessage(tabId, message, callback); }
  });
}

// Content script
var injected;

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

Solution 3: Indiscriminate Injection on Initialization

<code class="js">chrome.tabs.query({}, function(tabs) {
  for(var i in tabs) { chrome.tabs.executeScript(tabs[i].id, {file: "content_script.js"}); }
}); </code>

The above is the detailed content of How to Send Messages from a Background Script to a Content Script and then to an Injected 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