从弹出窗口到内容脚本的Chrome扩展消息传递

时间:2015-01-10 04:39:20

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

我正在尝试从popup.js向content.js发送消息,但我不明白为什么它不起作用。

这是我的设置:

的manifest.json

{
    "manifest_version": 2,

    "name": "Form Builder",
    "description": "This extension populates a form.",
    "version": "0.1",

    "content_scripts": [{
        "all_frames": true,
        "matches": ["http://*/*", "https://*/*"],
        "js" : [
            "/js/jquery/jquery.min.js", 
            "/js/formLoader.js",
            "/js/content.js"
        ]
    }],

    "options_page": "/html/options.html",
    "permissions": ["https://localhost:8443/", 
                    "tabs", "activeTab", "storage", "background"
    ],
    "icons": { "16": "/images/icons/wb_icon_16.png",
               "48": "/images/icons/wb_icon_48.png",
              "128": "/images/icons/wb_icon_128.png" 
    },
    "browser_action": {
        "default_popup": "/html/popup.html"
    }
}

content.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
    sendResponse("received message: " + request);
    formLoader.setFormData(request, sendResponse);

    // Why isn't this getting executed when I send a message from popup?

    sendResponse("Thank you");
});

popup.js

var popup = {
    // a few parts snipped out for brevity
    sendMessage: function(message) {
        chrome.tabs.sendMessage(tab.id, message, function(message) {
            console.log(chrome.runtime.lastError);
            popup.handleCallbacks(message);
        });
    },
    handleCallbacks: function (message)  { 
        console.log("handleCallbacks: " + message);
    }
}

formLoader.js

var formLoader = {
    init : function() {
        $("#PostingBody").val("formLoader.init");
    },
    setFormData: function(data, callback) {
        callback("[formLoader.js] got data: " + data);
    }
}

formLoader.init();

当我做类似的事情时:

popup.sendMessage(data);

在我的控制台中,我得到:

Object {message: "Could not establish connection. Receiving end does not exist."}
handleCallbacks: undefined

为什么没有接收端?我在content.js中的监听器做错了什么?

1 个答案:

答案 0 :(得分:0)

感谢: This answer from another question

对于Chrome 26+,请使用chrome.runtime.onMessage和chrome.runtime.sendMessage。

即使我很肯定,我发现有几个页面和参考文献没有提到这一点。