12

我是Google Chrome浏览器扩展程序的新手,我为我们的网站创建了一个用于检查您所在页面的内容,并基于此获取服务器的ID(我们有拥有4台虚拟机的webfarm)。现在使用服务器ID,我不想更改扩展名图标以在那里显示数字。我已经尝试使用:更改Chrome浏览器扩展程序图标

chrome.browserAction.setIcon({ 
    path : folder + icons[2], 
    tabId: tab.id 
}); 

但我发现了这个错误:chrome.browserAction is not available: You do not have permission to access this API. Ensure that the required permission or manifest property is included in your manifest.json.

我试着用搜索引擎的错误,并已通过文件搜索,但找不到是什么原因造成这...

+0

你有没有定义'browser_action'在你的清单中?在你的清单中遗漏的是我能想到的唯一一件事会导致这样的错误(除了使用canary/dev/beta版本的浏览器外)。 – apsillers

+0

' “browser_action”:{ “default_icon”: “数字/ 1green.png”, “default_popup”: “index.html的” }' 就是我.. – Richard

+0

我在我的 “正常” 的尝试Chrome在开发模式和加纳利 – Richard

回答

18

内容脚本无法访问大多数扩展API。相反,您需要使用message passing让内容脚本警报通知后台页面需要完成哪些工作。

你的内容脚本将送使用chrome.runtime.sendMessage的消息,并且后台页面应该听使用chrome.runtime.onMessage.addListener

内容脚本

if(shouldChangeIcon) { 
    // send message to background script 
    chrome.runtime.sendMessage({ "newIconPath" : folder + icons[2] }); 
} 

背景页面

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) { 
     // read `newIconPath` from request and read `tab.id` from sender 
     chrome.browserAction.setIcon({ 
      path: request.newIconPath, 
      tabId: sender.tab.id 
     }); 
    }); 
+0

好的,有什么方法可以跟踪背景中发生的事情吗?现在已经设置好了,但图标没有改变。已经获得了在'background'中声明的background.js和作为'content_script'的myscript.js。在myscript.js中引发'console.log()'的东西确实有效,但仍然是相同的图标.. – Richard

+1

也许你可以使用[在Chrome扩展中从何​​处读取background.js中的控制台消息?](http:// stackoverflow.com/a/10258029/710446) – apsillers

相关问题