How to fetch URL of current Tab in my chrome extension using javascript

google-chrome-extension, javascript, url

Solution

Note you must have the `tabs` permission set in your manifest file

"permissions": [
    "tabs"
],

http://developer.chrome.com/extensions/tabs.html

or the `activeTab` permission if initiated by a click on the extension button[Xan]

https://developer.chrome.com/extensions/activeTab

Code:

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

Problem

I am just getting started with Google Chrome Extension development and my project involves making an extension which when clicked prints the URL of whichever page/tab is currently open. So if I am on google's home page and I click my extension, I need to get "https://www.google.com/" as my output within the extension. I need to do this using javascript and am unable to find code which I understand and which does the job. I read about using "window.location" and "document.href" and stuff but won't that give me the url of just my extension and not the current tab? Please help me get started. Thanks in advance.

Original source