2012-05-29 147 views
0

我正在处理一个Chrome扩展,并且我需要在选项卡关闭时获取事件,以便我可以向服务器发送帖子。这是我所拥有的。谷歌浏览器,关闭标签事件监听器

chrome.tabs.onRemoved.addListener(function (tabId) { 
    alert(tabId); 
}); 

但我不能得到它的工作。任何人有任何想法?

编辑:

当我运行它,它说

Uncaught TypeError: Cannot read property 'onRemoved' of undefined

EDIT2:manifest.json的

{ 
"name": "WebHistory Extension", 
"version": "1.0", 
"manifest_version": 2, 
"description": "storing webhistory", 
    "content_scripts":[ 
     { 
      "matches": ["http://*/*"], 
      "js": ["jquery-1.7.min.js","myscript.js"], 
      "run_at": "document_end" 
     } 
    ], 
    "permissions" : ["tabs"] 
} 
+0

看起来像正确的方式去 - [根据文档](http://code.google.com/chrome/extensions/tabs.html#event-onRemoved)有任何错误? – ManseUK

+0

当我运行它时,它说“Uncaught TypeError:无法读取未定义的属性'onRemoved' –

+0

因此,您的代码可能位于错误的地方。它是否在后台页面上执行?你有权设置“标签”吗?请提供您的'manifest.json'设置。 –

回答

1

不能在内容脚本中使用chrome.tabs API:

However, content scripts have some limitations. They cannot: Use chrome.* APIs (except for parts of chrome.extension)

source

您需要做的是在内容脚本和背景页面之间建立通信。背景页面访问chrome.tabs API:

These limitations aren't as bad as they sound. Content scripts can indirectly use the chrome.* APIs, get access to extension data, and request extension actions by exchanging messages with their parent extension.

source

一切都在内容脚本文件的前五个段落。