Chrome 拡張機能のバックグラウンドから挿入されたバックグラウンドへのスクリプト間通信の問題を解決するにはどうすればよいですか?

DDD
リリース: 2024-10-18 11:35:02
オリジナル
617 人が閲覧しました

How to Resolve Inter-Script Communication Issue in Chrome Extensions from Background to Injected Background?

Messaging Across Multiple Scripts in Chrome Extensions: From Background to Injected

Background

In the context of Chrome extensions, sending messages between scripts running in different environments can be challenging. Here's a detailed analysis and solution to the specific issue you're facing when attempting to send messages from the background script to a content script and subsequently to an injected script.

Problem:

Your code fails to send messages because of the way content scripts are injected into targets. Initially, content scripts are not present in existing tabs unless a page specifically triggers their injection. This means that when your background script tries to send a message to a tab upon extension load, there's no listener to receive it.

Solutions:

Solution 1: Message on Demand

Check if the content script is ready before sending messages:

// 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
      // Inject the script and then send the message
    }
  });
}
ログイン後にコピー
// Content
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if(request.ping) { sendResponse({pong: true}); return; }
  // Process messages
});
ログイン後にコピー

Solution 2: Inject and Execute Once

Inject the content script but ensure it only executes once:

// Background
function injectAndSend(tabId, message, callback){
  // Inject script and send message
}
ログイン後にコピー
// Content
var executed; // Flag to prevent multiple executions

if(!executed){
  executed = true;
  // Process messages
}
ログイン後にコピー

Solution 3: Inject Indiscriminately

Inject content scripts without relying on their presence:

// Background
chrome.tabs.query({}, function(tabs) {
  for(var i in tabs) {
    // Inject scripts and send messages
  }
});
ログイン後にコピー

Solution 4: Use Browser Action

Attach your messaging logic to a browser action for specific user interactions:

chrome.browserAction.onClicked.addListener(function() {
  // Process messages
});
ログイン後にコピー

Orphaned Content Scripts

An implication to consider is the phenomenon of orphaned content scripts. When an extension reloads, content scripts may not be properly cleaned up, leaving behind event listeners that can interfere with newly injected scripts.

Solution:

Implement a heartbeat mechanism to check the connection between the content script and the background script. If the heartbeat fails, the content script should deregister listeners and defer any actions.

Conclusion:

By understanding the behavior of content scripts in Chrome extensions and employing the appropriate messaging techniques, you can effectively send messages from the background script to content scripts and injected scripts.

以上がChrome 拡張機能のバックグラウンドから挿入されたバックグラウンドへのスクリプト間通信の問題を解決するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!