【问题标题】:Unable to send message from context menu to content script无法将消息从上下文菜单发送到内容脚本
【发布时间】: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


【解决方案1】:

this answer 得到启发,我修改了我的 backgroundContextMenus.js 如下:

function ensureSendMessage(tabId, message, callback){ 
  chrome.tabs.sendMessage(tabId, {ping: true}, function(response){ 
    if(response && response.pong) { // Content script ready
      chrome.tabs.sendMessage(tabId, message, callback);
    } else { // No listener on the other end
      console.log("Injecting script programmatically");
      chrome.tabs.executeScript(tabId, {file: "markr.js"}, function(){
        if(chrome.runtime.lastError) {
          console.error(chrome.runtime.lastError);
          throw Error("Unable to inject script into tab " + tabId);
        }
        // OK, now it's injected and ready
        console.log("Sending msg now");
        chrome.tabs.sendMessage(tabId, message, callback);
      });
    }
  });
}

chrome.runtime.onInstalled.addListener(function(){
    chrome.contextMenus.create({"title": "Testing",
                                "contexts": ["selection"],
                                "id": "testing"});
});

chrome.contextMenus.onClicked.addListener(function(info, tab){
    ensureSendMessage(tab.id, {greeting: "hello"});
});

然后我修改了ma​​rkr.js如下:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
    if(request.ping){ 
        sendResponse({pong: true}); 
        return; 
    }   
    console.log("Text toggled bold");
}); 

现在控制台日志正是人们所期望的:

控制台日志:

markr.js:11 文本切换为粗体

请记住,此日志是网页开发工具的当前控制台日志,而不是后台脚本的检查视图。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    相关资源
    最近更新 更多