首頁 > web前端 > js教程 > 如何透過內容腳本建立後台腳本與注入腳本的通訊?

如何透過內容腳本建立後台腳本與注入腳本的通訊?

DDD
發布: 2024-10-18 11:06:03
原創
431 人瀏覽過

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.

以上是如何透過內容腳本建立後台腳本與注入腳本的通訊?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板