6

I'm doing a chrome extension, and there is in the doc this statement about chrome.tabs.onActivated.

Whenever I try to place chrome.tabs.onActivated.addListener, it says Uncaught TypeError: Cannot call method 'addListener' of undefined.

The whole background.html :

<script>
chrome.tabs.onActivated.addListener(function(info) {
    var tab = chrome.tabs.get(info.tabId, function(tab) {
        localStorage["current_url"] = tab.url;
    });
});
</script>
Rob W
  • 341,306
  • 83
  • 791
  • 678
azenet
  • 379
  • 1
  • 6
  • 14

2 Answers2

12

The documentation is incomplete. As of Chrome 18, chrome.tabs.onActiveChanged is replaced with chrome.tabs.onActivated. In Chrome 17, the onActivated event did not exist.

chrome.tabs.onActivated.addListener( function(info) {
    var tabId    = info.tabId,
        windowId = info.windowId;
});
chrome.tabs.onActiveChanged.addListener( function(tabId, info) {
    tabId        = tabId;         // For comparison
    var windowId = info.windowId;
});

I obtained this function name by opening the console in the context of an extension, and inspecting the keys of chrome.tabs.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    PS. This was the command I used: `Object.keys(chrome.tabs).filter(function(name){return name.slice(0,2)=='on'});`, which returned: `["onCreated", "onUpdated", "onMoved", "onSelectionChanged", "onActiveChanged", "onHighlightChanged", "onDetached", "onAttached", "onRemoved"]` in Chrome 17. – Rob W Mar 31 '12 at 08:54
4

Nothing is wrong with your code, it should work just fine.

Just make sure your manifest has the tabs permission:

manifest.json

{
  "name": "My extension",
  "version": "1",
  "manifest_version": 2,
  "background": {
    "scripts": ["background.js"]
   },
  "permissions": [
    "tabs"
  ]
}

background.js

chrome.tabs.onActivated.addListener(function(info) {
    var tab = chrome.tabs.get(info.tabId, function(tab) {
        localStorage["current_url"] = tab.url;
    });
});
Mohamed Mansour
  • 39,445
  • 10
  • 116
  • 90
  • Everything is okay, I have the permission... The thing that actually disturb me is that "undefined" thing.. Is the doc wrong ? – azenet Mar 31 '12 at 08:31
  • When you debug it, do you see the context correct? Add a breakpoint in inspector and refresh the background page to read the variables. What Chrome version are you running? – Mohamed Mansour Mar 31 '12 at 08:35
  • The Doc is right, I just ran the above code and it works as expected. in Chrome 18.0.1025.142 – Mohamed Mansour Mar 31 '12 at 08:36
  • I think I just got why it doesn't work right... I have Chrome 17. I guess it's pretty new. Thanks for your help, I'll try after updating. – azenet Mar 31 '12 at 08:43
  • You are on an old browser :x and extremely vulnerable, yea update to version 18. – Mohamed Mansour Mar 31 '12 at 19:04