用于将消息从弹出窗口发送到内容脚本的chrome扩展

时间:2013-10-05 12:11:59

标签: javascript google-chrome-extension content-script message-passing

我正在开发一个扩展程序,当用户在弹出窗口上按下按钮时,我必须从linkedin配置文件页面中提取数据。我,正在将消息从popup.js页面传递给contentscript,作为回应,我将通过内容脚本从linkedin配置文件页面中提取数据,以便我可以在popup.html中显示它。但是,当我检查popup.html时,我收到了错误。错误是:

Port: Could not establish connection. Receiving end does not exist. lastError:29
Error in event handler for 'undefined': Cannot read property 'farewell' of undefined
TypeError: Cannot read property 'farewell' of undefined
    at chrome-extension://kdfgoafjicddfffdbfofdmckejemfije/popup.js:6:25
    at <error: illegal access>
    at Event.dispatchToListener (event_bindings:356:21)
    at Event.dispatch_ (event_bindings:342:27)
    at Event.dispatch (event_bindings:362:17)
    at Object.chromeHidden.Port.dispatchOnDisconnect (miscellaneous_bindings:258:27)

作为参考,我的清单文件是:

{
    "name": "SoftwareGrid",
    "version": "0.5",
    "icons": { "16": "icons/16.png","48": "icons/48.png", "128": "icons/128.png" },
    "description": "Shows user cresidentials on Linkedin",
    "permissions": [
        "cookies",
        "tabs",
        "http://www.linkedin.com/*"
    ],

    "browser_action": {
        "default_title": "Show Profile",
        "default_icon": { "16": "icons/16.png","48": "icons/48.png", "128": "icons/128.png" },
        "default_popup": "popup.html"
    },

    "background": {
        "scripts": ["jquery-1.7.2.min.js","background.js"]
    }, 

    "content_scripts": [{
        "matches": ["http://www.linkedin.com/*"],
        "all_frames": true,
        "js": ["jquery-1.7.2.min.js", "script.js"],
        "run_at": "document_end"
    }],

    "web_accessible_resources": [
        "icons/i1.png"
    ],

    "manifest_version": 2
}

我的popup.js文件:

function sendClicks() {
    console.log("popup.js > sendClicks()");

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
            console.log(response.farewell);
        });
    });

    console.log("avra' inviato?");
}

$(function() {
    console.log("popup.js > OMD Extension ready");
    $('#sendclicks').click(function(){
        sendClicks();
    });
});

我的内容文件

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

        if (request.greeting == "hello")
            sendResponse({farewell: "goodbye"});
});

Plz帮助!

1 个答案:

答案 0 :(得分:3)

您可能需要在清单中添加此内容:

"permissions" : ["tabs"]