消息传递Background.html - >内容脚本

时间:2011-03-29 15:54:38

标签: google-chrome-extension

我在background.html中有以下内容将sendRequest发送到contentcript ...

chrome.tabs.getSelected(null,function(tab)
    {
        chrome.tabs.sendRequest(tab.id,{req:"func"});
    }); 

然而,它似乎没有起作用。我做错了什么?

相关清单文件的部分......

 "background_page": "background.html",
"browser_action":
{
    "default_icon": "icon.png",
    "popup": "popup.html"
},
"permissions": [
    "tabs",
    "http://*/*",
    "https://*/*",
    "notifications",
    "contextMenus"
],
"options_page": "options.html",
"content_scripts": [
    {
        "matches": ["http://*/*","https://*/*"],
        "js": ["contentScript.js","jquery.js"],
        "all_frames": false
    }
],

... contentscript

    chrome.extension.onRequest.addListener(
 function(request, sender, sendResponse)
 {
switch(request.req)
{
        case "func":
        func();
        sendResponse({});
        break;
 default:
        sendResponse({});
 }
 });

2 个答案:

答案 0 :(得分:2)

在后台页面中进行此操作:

chrome.tabs.getSelected(null,function(tab)
{
    chrome.tabs.sendRequest(tab.id,{req:"func"}, function(response){
        alert(response.req); // Get The response
    });
}); 

在内容脚本上:

sendResponse({ req: 'Your Response' });

同时将您的清单更改为:

{
"background_page": "background.html",
"browser_action":
{
    "default_icon": "icon.png",
    "popup": "popup.html"
},
"permissions": [
    "tabs",
    "http://*/*",
    "https://*/*",
    "notifications",
    "contextMenus"
],
"options_page": "options.html",
"content_scripts": [
    {
        "matches": ["http://*/*","https://*/*"],
        "js": ["contentScript.js","jquery.js"],
        "all_frames": false
    }
],
"name" : "FirstExtension",
"version" : "1.0",
}

PS:清单上的名称和版本是必需的......

答案 1 :(得分:0)

您的代码运行正常。发送请求时,可能不会在该页面上加载内容脚本。在chrome.tabs.getSelected之前你有某种条件吗?您不能立即运行它,您需要确保首先加载选项卡。

PS。同样在您的清单中,您可能希望在内容脚本之前加载jquery。