在Chrome的扩展程序的背景页面的onClick事件上向内容脚本发送消息

时间:2014-01-04 06:43:28

标签: javascript html google-chrome-extension

我知道消息传递用于此目的但不知何故它不能处理我的后台页面的onClick事件。我得到以下例外:

Error in event handler for (unknown): TypeError: Cannot read property 'data' of undefined
    at chrome-extension://aimjdbbnlgjodealdppjdpligkbjbmmb/background.js:27:31
    at disconnectListener (extensions::messaging:338:9)
    at Function.target.(anonymous function) (extensions::SafeBuiltins:19:14)
    at Event.dispatchToListener (extensions::event_bindings:386:22)
    at Event.dispatch_ (extensions::event_bindings:371:27)
    at Event.dispatch (extensions::event_bindings:392:17)
    at dispatchOnDisconnect (extensions::messaging:293:27) 

以下代码:

的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

var currentURL = document.location.href;
$(document).ready(function(){

    $("#button").click(function()
    {
        alert( "Handler for .click() called." );
    });
});

chrome.extension.onMessage.addListener(function(msg, sender, sendResponse)
{
    alert(msg);
    if (msg.method == "getHTML")
      sendResponse({data: "Welcome from Content Script"});
});

background.js

$(document).ready(function()
{
    chrome.browserAction.onClicked.addListener(function(activeTab){
  var loaderURL = chrome.extension.getURL("dashboard.html");
  _tab = activeTab;
  chrome.tabs.create({ url: loaderURL });
});
    $("#button").click(function()
    {
        chrome.extension.sendMessage({method: "getHTML",param:"myParam"}, function(response)
        {
                alert(response.data);
        });
    });

});

我无法使用chrome.tabs.sendMessage因为onClick事件我无法找到标签ID

1 个答案:

答案 0 :(得分:2)

首先,您需要将已弃用的chrome.extension.onMessage替换为script.js中的 chrome.runtime.onMessage

主要问题是,要 send messages to content scripts ,您需要使用 chrome.tabs.sendMessage (这也需要知道标签ID)。<登记/> 实现此功能的一种简单方法是在打开dashboard.html视图时将标签ID作为查询参数传递,例如dashboard.html?tabId=XX(请参阅下面修改后的background.js)。

<强> background.js:

var queryStr = '?tabId=';
var loaderURL = chrome.extension.getURL('/popup/popup.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));
        $('#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(response.data);
                }
            });
        });
    }
});

如上所示,在Chrome API回调中检查 chrome.runtime.lastError 以查看是否有任何错误始终是个好主意。在您的情况下,您会看到一条错误,指出没有接收端,这将指向正确的方向。