需要将消息从上下文菜单发送到内容脚本

时间:2014-11-09 17:45:23

标签: javascript google-chrome google-chrome-extension

我正在编写一个小扩展,允许我轻松提交reddit链接。 此扩展程序添加了一个新的上下文菜单('提交页面')。如果用户右键单击并选择此菜单,则会在另一个选项卡中打开www.redddit.com/submit页面,并提交触发菜单的页面。

我添加了上下文菜单:

contextMenu.js

// Setup where the menu is presents;
// A list of [context, context menu text, id]
var redditURL = 'http://www.reddit.com/submit';
var contexts = [["page", "Submit page", "id-submitPage"], ["link", "Submit link", "id-submitLink"], ["editable", "Submit text", "id-submitText"], ["image", "Submit image", "id-submitImage"]];

// Add all menus to their context
contexts.forEach(function(element) {
    chrome.contextMenus.create({
        "title" : element[1],
        "contexts" : [element[0]],
        "id" : element[2]
    });
});

// Add actions to menus
chrome.contextMenus.onClicked.addListener(function(info, tab) {
    var submittedURL = tab && tab.url;
    if (info["menuItemId"] == "id-submitPage") {
        chrome.tabs.create({
            "url" : redditURL
        }, function(tab) {
            // After we create the tab we also send a message to the content
            // script associated with the page to intercept our info
            console.log(submittedURL);
            chrome.tabs.sendMessage(tab.id, {
                "url" : submittedURL,
                "type" : "submitPage"
            });
        });
    }
});

正如您在addListener中看到的那样,我使用chrome.tabs.sendMessage将我提交的网址发送到与redditURL相关联的内容脚本。

内容脚本: contextMenu-RedditSubmit.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    alert('here');
    console.log(sender.tab ? "from a content script:" + sender.tab.url : "from the extension");
});

清单文件:

...
    "background": {
        "scripts": ["contextMenu.js"],
        "persistent": false
    },
    "content_scripts": [
        {
            "matches": ["http://www.reddit.com/submit"],
            "js": ["contextMenu-RedditSubmit.js"],
            "run_at": "document_start"
        }
    ],
...

问题是我在contextMenu-RedditSubmit.js内容脚本中没有收到我的消息。我既看不到console.log,也看不到警报。有什么提示吗?

1 个答案:

答案 0 :(得分:2)

在事件document_start内容脚本执行之前发送您的消息。

要确保其有效,请切换为使用programmatic injection

chrome.tabs.create({
  "url" : redditURL
}, function(tab) {
  // After we create the tab we also send a message to the content
  // script associated with the page to intercept our info
  chrome.tabs.executeScript(
    tab.id,
    {file: "contextMenu-RedditSubmit.js"},
    function() {
      // Here, it is guaranteed that the script finished executing
      //  (or there was an error)
      chrome.tabs.sendMessage(tab.id, {
        "url" : submittedURL,
        "type" : "submitPage"
      });
    }
  );
});