0
  1. Documentation describes onActivated as:chrome.tabs.onActivated.addListener(function(object activeInfo) {...});

    Fires when the active tab in a window changes. [...]

  2. As a comment on his own answer to another question, @RobW says:

    The correct method is chrome.tabs.onActiveChanged, with the same signature as the non-existant chrome.tabs.onActivated.

  3. Finally, a sample extension uses onSelectionChanged seemingly for the same purpose:

    chrome.tabs.onSelectionChanged.addListener(function(tabId) {
      lastTabId = tabId;
      chrome.pageAction.show(lastTabId);
    });
    

What's the difference between onSelectionChanged and onActiveChanged? Why is there no documentation for onSelectionChanged? What should I use to listen to tab changes?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Shawn
  • 10,931
  • 18
  • 81
  • 126
  • Note: At the time of posting, I (and you) were using Chrome 17. The `onActivated` event **does** exist in Chrome 18. If you want to target Chrome <17, use `onActiveChanged` (equivalent alias to `onSelectionChanged`). – Rob W Apr 06 '12 at 07:49

1 Answers1

3

You should use onActivated (Chrome 18+ only) to listen for tab changes. onActiveChanged and onSelectionChanged are deprecated events.

In the source code (see attachment), the purpose of these events, and their usage. I've updated my previous answer with a small demo, for clarification.

This is the relevant part of the source code:

void ExtensionBrowserEventRouter::ActiveTabChanged(
    TabContentsWrapper* old_contents,
    TabContentsWrapper* new_contents,
    int index,
    bool user_gesture) {
  ListValue args;
  int tab_id = ExtensionTabUtil::GetTabId(new_contents->web_contents());
  args.Append(Value::CreateIntegerValue(tab_id));

  DictionaryValue* object_args = new DictionaryValue();
  object_args->Set(tab_keys::kWindowIdKey, Value::CreateIntegerValue(
      ExtensionTabUtil::GetWindowIdOfTab(new_contents->web_contents())));
  args.Append(object_args);

  // The onActivated event replaced onActiveChanged and onSelectionChanged. The
  // deprecated events take two arguments: tabId, {windowId}.
  std::string old_json_args;
  base::JSONWriter::Write(&args, &old_json_args);

  // The onActivated event takes one argument: {windowId, tabId}.
  std::string new_json_args;
  args.Remove(0, NULL);
  object_args->Set(tab_keys::kTabIdKey, Value::CreateIntegerValue(tab_id));
  base::JSONWriter::Write(&args, &new_json_args);

  Profile* profile = new_contents->profile();
  DispatchEvent(profile, events::kOnTabSelectionChanged, old_json_args);
  DispatchEvent(profile, events::kOnTabActiveChanged, old_json_args);
  DispatchEvent(profile, events::kOnTabActivated, new_json_args);
}
KeyKi
  • 2,693
  • 3
  • 12
  • 24
Rob W
  • 341,306
  • 83
  • 791
  • 678