5

我有一段时间试图在我的内容脚本中获取代码来与我的面板对话。(此扩展为开发工具添加了一个新面板。)从我的内容脚本中,我可以这样做:

chrome.extension.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

我可以在后台脚本中提取它没问题。

chrome.extension.onMessage.addListener(
 function(request, sender, sendResponse) {
 if (request.greeting == "hello") sendResponse({farewell: JSON.stringify(sender)});
});

但是我需要在我的 devtools JS 中接收我的消息。这样我就可以与我添加到开发工具的面板交谈。我怎样才能做到这一点?

4

1 回答 1

16

为了在Devtools 页面和多个内容脚本页面之间建立连接,后台页面用作中介。所以,想法是有一个通道 from devtoolstobackground和 from backgroundto content scripts。这是处理内容脚本的可变性质所需的通用方法execution time

您可以使用以下脚本作为 to 之间通信的devtools.js参考content scripts

清单.json

注册backgrounddevtoolscontent scripts到清单文件

{
    "name": "Inspected Windows Demo",
    "description": "This demonstrates Inspected window API",
    "devtools_page": "devtools.html",
    "manifest_version": 2,
    "version": "2",
    "permissions": [
        "experimental",
        "tabs"
    ],
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "myscript.js"
            ]
        }
    ]
}

开发工具.html

注册devtools.js符合 CSP

<html>

    <head>
        <script src="devtools.js"></script>
    </head>

    <body></body>

</html>

开发工具.js

//Created a port with background page for continous message communication
var port = chrome.extension.connect({
    name: "Sample Communication" //Given a Name
});
//Posting message to background page
port.postMessage("Request Tab Data");
//Hanlde response when recieved from background page
port.onMessage.addListener(function (msg) {
    console.log("Tab Data recieved is  " + msg);
});

myscript.js

//Handler request from background page
chrome.extension.onMessage.addListener(function (message, sender) {
    console.log("In content Script Message Recieved is " + message);
    //Send needed information to background page
    chrome.extension.sendMessage("My URL is" + window.location.origin);
});

背景.js

//Handle request from devtools   
chrome.extension.onConnect.addListener(function (port) {
    port.onMessage.addListener(function (message) {
        //Request a tab for sending needed information
        chrome.tabs.query({
            "status": "complete",
            "currentWindow": true,
            "url": "http://www.google.co.in/"
        }, function (tabs) {

            for (tab in tabs) {
                //Sending Message to content scripts
                chrome.tabs.sendMessage(tabs[tab].id, message);
            }
        });

    });
    //Posting back to Devtools
    chrome.extension.onMessage.addListener(function (message, sender) {
        port.postMessage(message);
    });
});

输出

您可以在页面中看到http://www.google.co.in/正在接收devtools

参考

您可以参考以下文档以获取更多信息。

于 2013-01-10T20:34:19.607 回答