我正在构建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
未定义,因此没有明显的错误!
答案 0 :(得分:0)
正如@wOxxOm所指出的,这里的问题是我试图JSONify一个复杂的对象。添加.toString有效。我的坏!