从popup.html发送消息到内容脚本时出错

时间:2014-05-15 11:36:19

标签: jquery html google-chrome-extension

我正在练习谷歌Chrome扩展开发。我试图从我的popup.js发送消息到content.js文件,我收到以下错误:

未捕获的ReferenceError:标签未定义

此错误出现在我的popup.js文件中。

以下是我的代码文件

manifst.json

{
"manifest_version": 2,

"name": "by-Surfers",
"description": "This extension is for practice...",
"version": "0.0.1",
"browser_action": {
    "default_icon": "icon.png",
    "default_title": "Click to speak with other surfers..",
    "default_popup": "popup.html"
},
"background": {
    "scripts": ["event.js"],
    "persistent": false
},
"permissions": [
      "tabs"
    ],
"content_scripts": [
    {
        "matches": ["http://*/*", "https://*/*"],
        "js": ["content.js"]
    }
]

}

Popup.html

<!DOCTYPE html>
<html>
<head>
<script src="jquery-2.1.1.min.js"></script>
<script src="popup.js"></script>
<style>
      body {
        min-width: 300px;
        overflow-x: hidden;
      }
    </style>
</head>
<body>
It will start now....
<button id='btn'>click me</button>
</body>
</html>

popup.js

$(document).ready(function(){
    $('#btn').click(function(){
        StartTab();
    });
});

function StartTab(){
        chrome.tabs.sendMessage(tabs[0].id, {greeting: "OpenDialog"}, function(response) {
                // console.log(response.farewell);
            });
    }

event.js

chrome.browserAction.setBadgeText({text: "CET"});

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
    switch(request.type) {
        case "dom-loaded":
            alert(request.data.myProperty);
        break;
    }
    return true;
});

function OpenContentScript(){

}

content.js

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");

        if (request.greeting == "OpenDialog"){
            RunIt();
        }
});

function Runit(){
    alert("it has started...");
}

请帮助!!!

1 个答案:

答案 0 :(得分:1)

问题是tabs[0].id,因为tabs未在任何地方定义。

如果您尝试发送到当前有效标签,可以尝试:

function StartTab(){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        chrome.tabs.sendMessage(
            tabs[0].id,
            {greeting: "OpenDialog"},
            function(response) {
                // console.log(response.farewell);
            }
        );
    });
}

我想你实际上是从类似的例子中复制了这段代码而忘记了query包装器。