0

I'm trying to build an Extension which sends data from the popup.html to the tab dome, but I can't get the sendMessage to work and I don't understand why. I'm following this guidline: https://developer.chrome.com/extensions/messaging.html

here are my sources:

manifest:
{
   "manifest_version": 2,
   "name": "OMG Campaign Preview Maker",
   "description": "Easy OMG Campaign Preview Maker",
   "background": {  "scripts": ["background.js"]},
   "version": "0.1",
   "content_scripts": [
        {
          "matches": ["http://*/*", "https://*/*"],
          "js": ["jquery-1.7.min.js", "content.js"]
        }
    ],
   "browser_action": {
      "default_icon": "logo_128.jpg",
      "popup": "popup.html",
      "default_popup": "popup.html"
   },
   "icons": {
      "128": "logo_128.jpg"
   }
}

popup.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.7.min.js"></script>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<h1>Clicks</h1>
<p>extra1:
  <input type="text" name="extraclicks[]" id="extra1">
  <br>
  extra2:
  <input type="text" name="extraclicks[]" id="extra2">
  <br>
  extra3:
  <input type="text" name="extraclicks[]" id="extra3">
  <br>
  <br>
  <input type="submit" name="sendclicks" id="sendclicks" value="Invia Clicks">
</p>
</body>
</html>

popup.js

function sendClicks(){
    console.log("popup.js > sendClicks()");
    var clicksArr = new Array();

    $("input[name='extraclicks\\[\\]']").each(function(i, value){
        clicksArr.push($(this).val());
    });

    chrome.tabs.getSelected(null, function(tab) {
        console.log("popup.js > tab id: "+tab.id)
        chrome.tabs.sendMessage(tab.id, {type:"clicks" },
            function(response) {
                console.log(response.msg);
            }
        );
    });
    console.log("avra' inviato?");
}

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

content.js

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("content.js > onMessage");

    if (request.type == 'clicks') {
        console.log("content.js > clicks");
        sendResponse({msg: "success"});
    }
});

While I can perfectly see the logs gnerated from popup.js in the console, I don't see any of the logs launched by content.js. What am I doing wrong?

4

2 回答 2

0

好吧,我很愚蠢......错误的是......我正在观看的检查员页面。content.js 中的“console.log”在TAB INSPECTOR CONSOLE上打印,而不是在扩展名上!

我希望它会帮助别人。

于 2013-03-22T12:29:47.520 回答
0

哎呀,我想你只是向 popup.js 本身发送消息......

popup.js 中的 getSelected 监听弹出选项卡的活动(它也是 chrome 中的选项卡)因此,选项卡 ID 实际上是弹出选项卡,而不是插入 content.js 的选项卡

BTW getSelected 已弃用。尝试替代方案? http://developer.chrome.com/extensions/tabs.html#method-getCurrent

于 2013-03-22T10:04:40.750 回答