从Chrome Extensions内容脚本接收消息到按钮Click事件的背景js文件

时间:2014-01-04 18:15:20

标签: javascript jquery google-chrome-extension

我的扩展程序会打开一个包含按钮的html页面(dashboard.html)。点击按钮,我想接收内容脚本发送的消息。不知怎的,我无法做到这一点。代码如下:

的manifest.json

{
    "manifest_version": 2,
    "name" : "My Ext",
    "description" : "XXX",
    "version" : "1.0",
    "permissions": [
        "tabs"
  ],
    "content_scripts" : [{
        "matches" : ["http://example.com/"],
        "js" : ["jquery.js","script.js"]
    }],
"background":{
  "scripts": ["jquery.js","background.js"]
},
    "browser_action": {
        "default_title": "XX"
      }
}

dashboard.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="jquery.js"></script>
    <script src="background.js"></script>
  </head>
  <body>
      <form>
      <textarea id="search"></textarea>
      <input id="button" type="button" value="Search" />
      </form>
  </body>
</html>

的script.js

    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  alert(response.farewell);
});

background.js

    var queryStr = '?tabId=';
var loaderURL = chrome.extension.getURL('dashboard.html') + queryStr;
$(document).ready(function ()
{
    chrome.browserAction.onClicked.addListener(function (tab) {
        chrome.tabs.create({ url: loaderURL + tab.id });
    });
    if (location.search && (location.search.indexOf(queryStr) === 0))
    {
        var tabID = parseInt(location.search.substring(queryStr.length));
        alert(tabID);
        $('#button').click(function ()
        {
          /********following COde is not producing any result **/
            chrome.runtime.onMessage.addListener(
              function(request, sender, sendResponse) {
                alert(sender.tab ?
                            "from a content script:" + sender.tab.url :
                            "from the extension");
                alert(request.greeting);
                if (request.greeting == "hello")
                  sendResponse({farewell: "goodbye"});
              });


        });

    }
});

1 个答案:

答案 0 :(得分:2)

我不明白为什么你需要从内容脚本发送消息,因为你可以使用sendResponse传回任何必要的数据,但是......


manifest.json

{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",

    "background": {
        "persistent": false,
        "scripts": ["background.js"]
    },

    "content_scripts": [{
        "matches":    ["*://*/*"],
        "js":         ["jquery.min.js", "content.js"],
    }],

    "browser_action": {
        "default_title": "Test Extension"
//        "default_icon": {
//            "19": "img/icon19.png",
//            "38": "img/icon38.png"
//        },
    },

}

background.js

var queryStr = '?tabId=';
var loaderURL = chrome.extension.getURL('dashboard.html') + queryStr;
chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.create({ url: loaderURL + tab.id });
});

content.js

chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    alert('Message from a view:\n'
          + JSON.stringify(msg));

    if (msg.method === 'getHTML') {
        sendResponse({ data: 'Welcome from Content Script' });
        chrome.runtime.sendMessage({
            body: 'Here I am, sending you another message !'
        });
    }
});

dashboard.html

<!DOCTYPE html>
<html>
    <head>
        <title>Dashboard</title>
        <script src="jquery.min.js"></script>
        <script src="dashboard.js"></script>
    </head>
    <body>
        <form>
            <textarea id="search"></textarea><br />
            <input type="button" id="button" value="Search" />
        </form>
    </body>
</html>

dashboard.js

var queryStr = '?tabId=';

chrome.runtime.onMessage.addListener(function(msg, sender) {
    alert('Message from: Tab ' + sender.tab.id + ' (using `sendMessage`)\n'
          + JSON.stringify(msg));
});

$(document).ready(function () {
    if (location.search && (location.search.indexOf(queryStr) === 0)) {
        var tabID = parseInt(location.search.substring(queryStr.length));
        $('#button').click(function () {
            chrome.tabs.sendMessage(tabID, {
                method: 'getHTML',
                param:  'myParam'
            }, function (response) {
                if (chrome.runtime.lastError) {
                    alert('ERROR: ' + chrome.runtime.lastError.message);
                } else {
                    alert('Message from: Tab ' + tabID
                          + ' (using `sendResponse`)\n'
                          + response.data);
                }
            });
        });
    }
});

还有一件事:

  • 您不需要tabs权限(至少对于当前显示的功能)。这是一个强大的权限,所以不要轻松使用(出于安全原因和不吓唬用户)。