Chrome扩展消息传递:sendResponse返回空对象

问题描述 投票:0回答:1

我正在构建Chrome扩展程序,我希望在用户单击上下文菜单后获取当前选定的文本。我正在尝试通过从后台脚本向内容脚本发送消息来执行此操作,但从内容脚本返回的对象始终为空。

这是相关的代码:

background_script.js:

function onClickHandler(info, tab){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {method: "getSelection"}, undefined, function(response){
            console.log(response.data); // <--- this is undefined
        });
    });
}

chrome.contextMenus.onClicked.addListener(onClickHandler);

content_script.js:

chrome.runtime.onMessage.addListener( 
    function(request, sender, sendResponse) {
        if (request.method == "getSelection"){
            var selection = window.getSelection(); // <--- this is ok
            sendResponse({data: selection}); 
            return true;
        }
    }
)

的manifest.json

{
    "manifest_version": 2,

    "name": "Browser Extension",
    "description": "Browser Extension",
    "version": "0.1",

    "background": {
        "scripts": [
            "background_script.js"
        ]
    },

    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content_script.js"]
        }
    ],

    "permissions": [
        "activeTab",
        "contextMenus",
        "storage"
    ]
}

在类似情况下的主要问题似乎是缺少return true;声明,但我补充说。此外,chrome.tabs.sendMessage函数有一个新参数options但是我省略它或传递未定义或空值没有区别。

谢谢 :)

编辑:sendMessage函数中的chrome.runtime.lastError未定义,因此没有明显的错误!

javascript google-chrome google-chrome-extension google-chrome-devtools
1个回答
0
投票

正如@wOxxOm所指出的,这里的问题是我试图JSON化一个复杂的对象。添加.toString有效。我的错!

© www.soinside.com 2019 - 2024. All rights reserved.