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>
위 내용은 백그라운드 스크립트에서 콘텐츠 스크립트로 메시지를 보낸 다음 삽입된 스크립트로 메시지를 보내는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!