首页 > web前端 > js教程 > 正文

如何通过内容脚本建立后台脚本与注入脚本的通信?

DDD
发布: 2024-10-18 11:06:03
原创
306 人浏览过

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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!