Chrome扩展消息在内容和后台之间传递

Chrome extension message passing between content and background

本文关键字:后台 之间 扩展 消息 Chrome      更新时间:2023-09-26

我已经对此进行了几个小时的测试,我还采取了一个在当时已知有效的例子。在这里看到的:https://stackoverflow.com/a/27829709/2430488

它只是不适合我或我不知道如何测试。我正在打开开发人员工具,也是扩展开发人员工具,但在任何窗口中都没有记录任何内容。

我使用的代码:

manifest.json

{
    "manifest_version": 2,
    "name": "Some test",
    "description": "https://stackoverflow.com/questions/27823740",
    "version": "0",
    "background": {
        "scripts": [
            "background.js"
        ] 
    },
    "permissions": ["tabs", "<all_urls>"],
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["cont.js"]
        }
    ]
}

cont.js

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {        
    if (msg.message && (msg.message == "DIMENSION")) {                          
        var dimension = getPageDiemension(document.documentElement);        
        console.log('Dimension:', dimension);
        sendResponse(dimension);       
    }
        return true;
});
getPageDiemension = function(currentDom){
    return {
        x: 0,
        y: 0,
        w: currentDom.scrollWidth,
        h: currentDom.scrollHeight
    }
}

background.js

getPageDimension = function (){
    chrome.tabs.query({active: true, highlighted: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { message: "DIMENSION" }, function(response){
            if (response !== null) console.log('Response:', response);
            else console.log('Response is null');
        });
    }); 
    };

请帮忙,我真的不知道我做错了什么,我一直在看文档在过去的几个小时,但我不明白为什么不工作。

谢谢。

正如rsanchez所提到的,您的背景定义了一个函数getPageDimension

它永远不会被调用,所以你的扩展什么也不做。似乎没有任何错误,你只是从来没有任何事情。

你需要绑定对getPageDimension的调用到一些事件,例如点击浏览器动作