38

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.

2

11 Answers 11

73

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); }); 
Sign up to request clarification or add additional context in comments.

5 Comments

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
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[] ?
You can check developer.chrome.com/extensions/tabs.html#method-query for more details on the parameters of the function.
Note: This no longer needs the tabs permission. If initiated by a click on the extension button, activeTab permission is sufficient.
tabs is such a heavy permission! Consider using: activeTab.
37

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

5 Comments

This is the most relevant answer and should be updated as the best answer.
@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 Kindly elaborate what u r trying to achieve and paste some code here so that we can solve it efficiently together.
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.
How we can get tab content/html ?
12

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!

Comments

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')}); 

Comments

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}); } }); 

1 Comment

chrome.tabs isn't even available from content scripts, so I'm not sure what race conditions you are referring to.
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); }); 

Comments

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.

Comments

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 }) 

1 Comment

This seems to be the most current way to implement this.
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) 

1 Comment

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?
-1

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.

2 Comments

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).
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
-1

JS:

let myLocationUrl = location.href; console.log(myLocation); 

1 Comment

What is myLocation? Or is this just a typo and should be myLocationUrl? Are you sure this is working from inside a chrome extension?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.