2012-05-29 146 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

一切都在內容腳本文件的前五個段落。