Darth Coder
Darth Coder

Reputation: 1798

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

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.

Upvotes: 38

Views: 75837

Answers (11)

SubWay74
SubWay74

Reputation: 7

JS:

let myLocationUrl = location.href;

console.log(myLocation);

Upvotes: -1

sarvesh_r
sarvesh_r

Reputation: 519

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

Upvotes: 3

Musa
Musa

Reputation: 97672

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

Upvotes: 73

Piers Uso Walter
Piers Uso Walter

Reputation: 369

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

Upvotes: 2

Shashiraj
Shashiraj

Reputation: 79

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)

Upvotes: 1

Prem Santh
Prem Santh

Reputation: 334

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

Upvotes: 1

Rich Werden
Rich Werden

Reputation: 1657

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.

Upvotes: 1

Clint Eastwood
Clint Eastwood

Reputation: 5698

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!

Upvotes: 11

jayant singh
jayant singh

Reputation: 889

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

Upvotes: 1

Kamil
Kamil

Reputation: 1641

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.

Upvotes: -1

saadsaf
saadsaf

Reputation: 1451

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

Upvotes: 37

Related Questions