2014-05-15 20 views
0

我正在练习Google Chrome扩展开发。我试图从我popup.js发送消息给content.js文件,我收到以下错误:将popup.html发送至内容脚本的错误

未捕获的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

问题是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包装。

+0

thnx man ...我犯了这样一个愚蠢的错误! – Savaratkar

相关问题