11

I'm making a google chrome extension, and I need to get the current page URL and title. How can I achieve this?

serg
  • 109,619
  • 77
  • 317
  • 330

2 Answers2

17
chrome.tabs.getSelected(null, function(tab) { //<-- "tab" has all the information
    console.log(tab.url);       //returns the url
    console.log(tab.title);     //returns the title
});

For more please read chrome.tabs. About the tab object, read here.


Note: chrome.tabs.getSelected has been deprecated since Chrome 16. As the documentation has suggested, chrome.tabs.query() should be used along with the argument {'active': true} to select the active tab.

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    tabs[0].url;     //url
    tabs[0].title;   //title
});
Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • For anyone seeing this lately, it's worth pointing out that chrome.tabs.getSelected() has been deprecated, and Konstantin's answer is now the correct answer to this question. – bmelton Mar 25 '14 at 18:04
  • Note that "currentWindow" doesn't refer to what you probably think it refers to. You most likely want to use "lastFocusedWindow", which is the window in focus, in conjunction with "active", which is the tab in focus. – V. Rubinetti Jul 19 '16 at 03:06
7

The method getSelected() has been deprecated since Google Chrome 16 (but many articles in the official documentation had not yet been updated). Official message is here. To get the tab that is selected in the specified window, use chrome.tabs.query() with the argument {'active': true}. So now it should looks like this:

chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
  console.log(tabs[0].url);
  console.log(tabs[0].title);
});

Edit: tabs[0] is the first active tab.

Dorian
  • 22,759
  • 8
  • 120
  • 116
Konstantin Smolyanin
  • 17,579
  • 12
  • 56
  • 56