35

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.

Chris Moschini
  • 36,764
  • 19
  • 160
  • 190
Darth Coder
  • 1,738
  • 7
  • 33
  • 56
  • possible duplicate of [How to get current URL in Chrome on click of the button](http://stackoverflow.com/questions/17379190/how-to-get-current-url-in-chrome-on-click-of-the-button) – Rob W Aug 26 '13 at 12:37
  • SOLUTION: https://stackoverflow.com/a/58687656/6546261 – Prem Santh Nov 04 '19 at 05:34

11 Answers11

70

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);
});
wOxxOm
  • 65,848
  • 11
  • 132
  • 136
Musa
  • 96,336
  • 17
  • 118
  • 137
  • 3
    Umm I tried the code but it's not working. This is the error I get on the console: Uncaught TypeError: Cannot read property 'url' of undefined – Darth Coder Aug 26 '13 at 04:25
  • 1
    Great :D The second solution works fine Thanks. Can you please explain the answer as well? I mean what does active:true indicate when we are already using currentWindow:true? also, what exactly will be the contents of tabs[] ? – Darth Coder Aug 26 '13 at 04:48
  • 1
    You can check http://developer.chrome.com/extensions/tabs.html#method-query for more details on the parameters of the function. – Métoule Aug 26 '13 at 11:27
  • 6
    **Note:** This no longer needs the `tabs` permission. If initiated by a click on the extension button, `activeTab` permission is sufficient. – Xan Aug 14 '14 at 08:19
  • 1
    `tabs` is such a heavy permission! Consider using: [`activeTab`](https://developer.chrome.com/extensions/activeTab). – Константин Ван Jul 20 '16 at 12:53
35

Using javascript, it will work if you are not using it in popup because javascript in popup will return url of popup therefore, in popup, you have to use Chrome tab API and set permission in Chrome manifest.

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

So best way is to use Chrome tab API

Lucas
  • 3,376
  • 6
  • 31
  • 46
saadsaf
  • 1,421
  • 1
  • 17
  • 28
  • 5
    This is the most relevant answer and should be updated as the best answer. – Ben Oct 23 '14 at 09:07
  • @saadsaf I'm having a really hard time figuring out how to fork tabs[0].url out of this callback though. Should it/Can it only be used in the query's callback function? – A13X Mar 28 '17 at 21:04
  • @A13X Kindly elaborate what u r trying to achieve and paste some code here so that we can solve it efficiently together. – saadsaf Mar 29 '17 at 05:40
  • 1
    Nevermind. I was trying to set a global variable that was already declared in my popup.js to the `tab[0].url`. It kept returning undefined. I instead opted to directly put the query() in my window.onload and do an injection of the HTML doc I want (to display the url). It works. – A13X Apr 01 '17 at 00:43
  • How we can get tab content/html ? – Krishan Kumar Nov 04 '22 at 06:41
10

You need to be careful with what you mean by "current tab". If the user has more than one window open, each of them with multiple tabs, Chrome defines the "current window" as the one that is running the content script that makes use of the chrome.tabs API. That happened to me and I solved it by referencing not the "current" window but the last focused one:

chrome.tabs.query({ active: true, lastFocusedWindow: true }, function (tabs) {
    // Do something
});

References:

https://developer.chrome.com/extensions/windows#current-window https://developer.chrome.com/extensions/tabs#method-query

Hope it helps!

Clint Eastwood
  • 4,995
  • 3
  • 31
  • 27
3

Update : If you are on manifest version 3 then proceed with the following,

 async function getCurrentTab() {
 let queryOptions = { active: true, currentWindow: true };

  let [tab] = await browser.tabs.query(queryOptions);
  localStorage.setItem('tabname' , tab);
   return tab;
  }

 getCurrentTab()
 .then((data) => { console.log('newdata',data)})
 .then(() => { console.log('error')});
sarvesh_r
  • 340
  • 1
  • 4
2

Please be aware that chrome.tabs.query() and chrome.tabs.getCurrent will run into race conditions when called in short order from multiple content scripts.

The returned tab will not necessarily be the tab of the requestor.

An easier way to do this is to send a message to the background thread. This message includes the sending tab as the tab parameter.

The background thread can take this parameter and directly include it in its response to the message.

Not only does this prevent race conditions, it's also faster because it does not use an asynchronous operation (unlike the call to chrome.tabs.query())

Example:

Content script

var myTab;
chrome.runtime.sendMessage({ message: "get_tab_msg" }, (response) => {
    myTab = response.tab;
});

Background script

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.message === "get_tab_msg") {
        // The content script has asked for the tab.
        sendResponse({tab: sender.tab});
    }
});

Piers Uso Walter
  • 359
  • 4
  • 10
1

this worked for me give it a try

chrome.tabs.query({
active: true,
lastFocusedWindow: true
}, function(tabs) {
// and use that tab to fill in out title and url
var tab = tabs[0];
console.log(tab.url);
alert(tab.url);
 });
jayant singh
  • 929
  • 12
  • 17
1

DO NOT use getSelected

As per the Chrome Developer Docs: chrome.tabs.getSelected has been deprecated since Chrome ver.33

Instead use:

chrome.tabs.query({active:true}, __someCallbackFunction__) like Musa's second suggestion.

Community
  • 1
  • 1
Rich Werden
  • 1,190
  • 11
  • 11
1

Here is the answer your looking for without adding new tabs permissions

chrome.browserAction.onClicked.addListener(function(e){
     console.log(e.url); 
     //give you the url of the tab on which you clicked the extension
})
Prem Santh
  • 324
  • 2
  • 10
1

The solutions posted here somehow did not worked for me but below snippet worked without any issues-

let currentURL = window.location.href;
console.log(currentURL)
Dharman
  • 30,962
  • 25
  • 85
  • 135
Shashiraj
  • 79
  • 4
  • Interesting, this worked for me as well when none of the other solutions above did. My question though; is this bad practice for production? Could this potentially return inaccurate values? – Justin Morrison Dec 29 '21 at 01:49
0

UPDATE: this method is now deprecated, so please don't use it

In my case any above has not worked. So I used this:

chrome.tabs.getSelected(null, function(tab) {
    console.log(tab.url)
})

and it worked great! Hope it helps.

Kamil
  • 1,633
  • 2
  • 21
  • 24
  • getSelected() has been deprecated and shouldn't be used. chrome.tabs.query({active: true, currentWindow: true}, function (arrayOfTabs) { console.log(tabs[0].url); }); is the current way to get the current tab (and URL). – Michael Oryl Aug 13 '14 at 13:46
  • use 'activeTab' permission on manifest and try chrome.tabs.query({active: true},function(tab){console.log(tab)}) It should work Its not recommended to use getSelected() as its deprecated – Prem Santh Nov 04 '19 at 05:23
0

JS:

let myLocationUrl = location.href;

console.log(myLocation);
SubWay74
  • 9
  • 1
  • What is `myLocation`? Or is this just a typo and should be `myLocationUrl`? Are you sure this is working from inside a chrome extension? – BDL Mar 14 '22 at 09:42