无法多次发送chrome-extension消息

时间:2015-06-19 12:27:27

标签: javascript jquery google-chrome-extension

我在我的应用中使用chrome扩展长期连接。在第一次我发送消息都很好,但在第二次我得到异常:“试图使用断开的端口对象”。 我的代码(我删除了所有的代码):

content.js:

    var port = chrome.runtime.connect({name: "letmeknow"});
    function checkIf_hiddenDiv_wasChanged()                
    {
        try
        {
            port.postMessage({message: contentScriptMessage});
        }
        catch(err) 
        {
          ;
        }
    }
    port.onMessage.addListener(function(msg) {
        try
        {
            messageData=msg.data;
            alert('content received: '+messageData);
        }
        catch(err)
        {
            ;
        }
     });

background.js:

chrome.runtime.onConnect.addListener(function(port) {
    console.assert(port.name == "letmeknow"); 
    port.onMessage.addListener(function(msg) 
    {
        try
        {
            returnMessage(port, msg.message);
        }
        catch(err)
        {
            ;
        }
    });
});
//==============================================//
function returnMessage(port, messageToReturn)
{
    try
    {
        chrome.tabs.getSelected(null, function(tab) 
        {
            var joinedMessage = messageToReturn + '***' +backgroundScriptMessage;       
            alert('bg send: '+joinedMessage);
            alert(port.name);
            port.postMessage({data: joinedMessage});
            alert(port.name);
        });
    }
    catch(err)
    {
        ;
    }
}

的manifest.json:

{
    "manifest_version": 2,
    "name": "MyApp",
    "version": "1.0",

    "browser_action": 
    {
        "default_icon": "icon.png",
        "default_popup": "mainpage.html"
    },

    "background": 
    {
        "page": "mainpage.html"
    },

    "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

    "content_scripts": 
    [
        {
        "matches": ["<all_urls>"],
        "js": ["content.js"]
        }
    ], 

    "permissions": ["tabs","cookies","activeTab","https://api.domain.com/","<all_urls>"]

}

我做错了什么? (我看到'var port = chrome.runtime.connect ...'中的一些版本在background.js中定义。我现在需要这个定义。)

0 个答案:

没有答案