数据未在Chrome扩展中从弹出窗口传递到背景

时间:2014-07-07 09:15:35

标签: javascript jquery google-chrome google-chrome-extension

我认为我掌握了它,但它只是不起作用......我无法弄清楚原因。

清单:

{
  "name": "Dummy Extension",
  "description": "Dummy Extension Description",
  "version": "2.0",
  "permissions": [
    "activeTab"
  ],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_title": "Dummy Extension",
     "default_popup": "popup.html"
  },
  "manifest_version": 2,
  "content_scripts": [ {
    "js": [ "jquery.min.js", "background.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }]
}

背景:

chrome.extension.onMessage.addListener( function(request,sender,sendResponse)
{
    if( request.greeting === "GetURL" )
    {
        var tabURL = "Not set yet";
        chrome.tabs.query({active:true},function(tabs){
            if(tabs.length === 0) {
                sendResponse({});
                return;
            }
            tabURL = tabs[0].url;
            sendResponse( {navURL:tabURL} );
        });        
    }
}

Popup.html

<!DOCTYPE html>
<head>
<script src='popup.js'></script>
<script src='jquery.min.js'></script>
</head>
<body>
    Hello World!
        <br />
    <input id="tabURL" type="text" />
        <br />
    <input value="SEND!" type="button" id="send" />
</body>
</html>

和popup.js

function getURL() {
    chrome.extension.sendMessage({greeting: "GetURL"},
        function (response) {
            tabURL = response.navURL;
            $("#tabURL").val(tabURL);
        });
}

$("#send").click(getURL());

我只能弄清楚什么是错的,定义了jquery,我没有得到控制台错误。 任何帮助都会很棒!

1 个答案:

答案 0 :(得分:2)

在完全构造DOM并失败之前,

$("#send").click(getURL());被执行。此外,您需要将引用传递给getURL,而不是执行它。

修复:

$(document).ready(function(){
  $("#send").click(getURL);
});

顺便说一下,您可能会在错误的控制台中查找错误。有关弹出窗口,请参阅this debugging tutorial