>  기사  >  웹 프론트엔드  >  백그라운드 스크립트에서 콘텐츠 스크립트로 메시지를 보낸 다음 삽입된 스크립트로 메시지를 보내는 방법은 무엇입니까?

백그라운드 스크립트에서 콘텐츠 스크립트로 메시지를 보낸 다음 삽입된 스크립트로 메시지를 보내는 방법은 무엇입니까?

Barbara Streisand
Barbara Streisand원래의
2024-10-18 12:04:26182검색

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>

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

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.