Chrome扩展程序,如何将消息从面板发送到内容脚本

Chrome extension, how to send message from panel to content script

本文关键字:脚本 程序 扩展 消息 Chrome      更新时间:2023-09-26

My contentScript 向 backgroundScript 发送一条消息,打开一个弹出窗口/面板/窗口。此面板加载外部网页。我在面板中注入了一些 javascript 来与之交互。

我现在要做的是将数据从面板发送到"主页"(contentScript)。我已经成功地将消息从面板发送到后台脚本。

我不明白/不知道的是如何将数据从backgoundScript传递到contentScript。

根据@Haibara Ai的评论更新脚本

清单.js

{
"name": "My extension",
"version": "0.1",
"manifest_version": 2,
"description": "description",
"permissions": ["activeTab", "tabs","http://*/*","https://*/*"],
"content_scripts": [
    {
        // Change 'matches' attribute to load content
        // script only in pages you want to.
        "matches": ["SomeUrl"],
        "js": ["jquery.min.js", "contentscript.js", "notifier.js"]
    }
],
"background": {
    "scripts": ["eventPage.js"],
    "persistent": false
}
}

内容脚本.js

$(document).ready(function() {
    var link = document.getElementById('inputLink');
    // onClick's logic below:
    link.addEventListener('click', function() {
        chrome.runtime.sendMessage({
            action: 'createWindow',
            url: $('input[name=link]').val()
          }, function(message) {
            console.log(message);
            })
    });
});
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) { 
    alert('a');
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
});

事件页面.js

chrome.runtime.onMessage.addListener(function(request) {
    if (request && request.action === 'createWindow' && request.url) {
        chrome.windows.create(
            {
                url: request.url,
                focused: true,
                incognito: true,
                type: "panel"
            }, function (newWindow) {
                chrome.tabs.executeScript(newWindow.tabs[0].id, {
                    file: "jquery.min.js"
                }, function() {
                    chrome.tabs.executeScript(newWindow.tabs[0].id, {
                        file: "htmlselection.js"
                    });
                });
                chrome.tabs.insertCSS(newWindow.tabs[0].id, {file: "htmlselection.css"});
        });
    } else {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
            console.log(chrome.tabs);
            chrome.tabs.sendMessage(tabs[0].id, {action: "SendIt"}, function(response) {});  
        });
    }
});

html选择.js(注入弹出窗口/面板/窗口中)

[...]
//After a click within the popup/panel/window
chrome.runtime.sendMessage({ text: 'test' });
[...]

谢谢你的帮助。

已更新

如果要在 chrome.runtime.onMessage 内发送消息,只需使用回调sendResponse或使用sender.tab.id作为 tabId 来发回消息。

您的代码还有其他问题:

  1. 由于您使用编程注入来注入脚本,因此您应该在"web_accessible_resources"中声明它们manifest.json

    "web_accessible_resources": [
        "htmlselection.js",
        "jquery.min.js",
        "htmlselection.css"
    ]
    
  2. 在您的内容脚本.js中,只需删除消息部分,因为您在此脚本中没有收到任何内容。

  3. 对于事件页.js,请使用sendResponse而不是tab.query

    else {
        console.log("2");
        sendResponse({ action: "SendIt" });
    }
    

以前

查看消息传递,您可以使用以下代码片段从后台页面发送消息:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});

修复了代码片段的版本:

chrome.tabs.query({active: true, currentWindow: false}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
    console.log(response.farewell);
  });
});

设置currentWindow:false,它起作用了。