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.
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.
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 && 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!