【发布时间】:2018-06-12 17:17:36
【问题描述】:
当用户选择上下文菜单项时,我想向内容脚本发送消息。然后,内容脚本将根据消息,根据需要格式化网页。
我无法这样做,我已经能够将问题定位到负责发送消息的代码(在上下文菜单脚本中)或负责接收消息的代码(在内容脚本中)。
下面,我尝试展示一个试图复制问题的代码的简化版本:
manifest.json
{
"manifest_version": 2,
"name": "MCVE for SO",
"version": "1",
"description": "Demonstrate message passing from context menu to content script",
"author": "Nityesh Agarwal",
"permissions": [
"tabs",
"activeTab",
"contextMenus"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["markr.js"]
}
],
"background": {
"scripts": ["backgroundContextMenus.js"]
}
}
backgroundContextMenus.js:
chrome.runtime.onInstalled.addListener(function(){
chrome.contextMenus.create({"title": "Testing",
"contexts": ["selection"],
"id": "testing"});
});
chrome.contextMenus.onClicked.addListener(function(info, tab){
console.log("testing..");
console.log("Before sending the bold message");
chrome.tabs.sendMessage(tab.id, {changeParameter: "bold"});
console.log("After sending the bold message");
});
markr.js:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse){
console.log("Text toggled bold");
});
选择上下文菜单项后,console 会显示以下消息:
backgroundContextMenus.js:8 测试..
backgroundContextMenus.js:9 发送粗体消息之前
backgroundContextMenus.js:11 发送粗体消息后
因此,您可能会注意到,没有日志说类似
文本切换为粗体
这意味着markr.js 文件中的代码没有被执行。因此,我怀疑负责发送消息的代码一定有问题:chrome.tabs.sendMessage(tabs[0].id, {changeParameter: "bold"});)
这是我试图复制的另一个代码 sn-p,但它给出了同样的问题 - https://stackoverflow.com/a/14473739/7082018
我无法弄清楚它到底有什么问题。如果有人可以帮助告诉我如何能够在上下文菜单和内容页面之间成功传递消息,那将是非常有帮助的。
【问题讨论】:
-
chrome.tabs.query 不需要 - 您在 onClicked 回调中有
tab,所以只需发送到tab.id。 -
注意,网页有自己的控制台,内容脚本的实例也在那里运行。
-
@wOxxOm 是的,你是对的。我已经删除了
chrome.tabs.query,现在我正在使用tab.id,但这并不能缓解问题。我仍然无法在控制台中获得所需的日志,即“文本切换为粗体”。 -
听起来您的内容脚本实际上并未在网页上运行。您可以在网页的 devtools、Sources 面板、Content scripts 子面板中检查它的存在。
-
是的,我的内容脚本没有显示在该面板上。知道我怎么能做到这一点吗? @wOxxOm
标签: javascript google-chrome-extension contextmenu content-script