I'm having fun with Google Chrome extension, and I just want to know how can I store the URL of the current tab in a variable?
11 Answers
Use chrome.tabs.query()
like this:
chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
let url = tabs[0].url;
// use `url` here inside the callback because it's asynchronous!
});
You'll need to request tabs
or activeTab
permission in your extension manifest:
"permissions": [ ...
"tabs"
]
or
"permissions": [ ...
"activeTab"
]
Prefer activeTab
if your code uses chrome.tabs.query after the user explicitly invoked the extension (clicked its icon or its context menu item or pressed its chrome.commands
hotkey) because this permission doesn't add any warnings when installing the extension, unlike tabs
that adds Read your browsing history
which may scare some users.
It's important to note that the definition of your "current tab" may differ depending on your extension's needs.
Setting lastFocusedWindow: true
in the query is appropriate when you want to access the current tab in the user's focused window (typically the topmost window).
Setting currentWindow: true
allows you to get the current tab in the window where your extension's code is currently executing. For example, this might be useful if your extension creates a new window / popup (changing focus), but still wants to access tab information from the window where the extension was run.
I chose to use lastFocusedWindow: true
in this example, because Google calls out cases in which currentWindow
may not always be present.
You are free to further refine your tab query using any of the properties defined here: chrome.tabs.query

- 65,848
- 11
- 132
- 136

- 3,925
- 2
- 20
- 21
-
36Why is the url always undefined? – nnm May 31 '14 at 12:27
-
6If url is undefined try reloading your extension from chrome://extensions This will reload the extension's config and apply the newly added "tabs" permission. – flashbackzoo Apr 16 '16 at 23:34
-
6url is undefined because http://stackoverflow.com/questions/28786723/why-doesnt-chrome-tabs-query-return-the-tabs-url-when-called-using-requirejs (answer: close your dev tools window or change to currentWindow instead of lastFocusedWindow) – kspearrin Sep 14 '16 at 03:01
-
2I got undefined when my dev tools window was undocked. Docking it fixed the undefined issue. – Fisu Mar 06 '18 at 13:30
-
1This doesn't return the variable url to the caller. I would like a simple function url=GetCurrentTabUrl() that returns the current tab url to the caller. Here the variable is inside the callback function. I can pass it to another function but it makes the code structure akward. I would like also to avoid using global variables. any idea @thauburger? – Thierry Dalon Mar 11 '20 at 09:51
-
@ThierryDalon You could use `async/await` I guess. – Camilo Nov 25 '20 at 03:04
-
This answer sadly neglects to mention that you can't access the chrome.tabs area inside of a content script. See: https://stackoverflow.com/a/35523438/1576548 – Raleigh L. Mar 14 '21 at 07:29
-
This will give you the wrong url – pabloRN Feb 14 '22 at 12:22
-
How would you get the URL on the initial request? So before any redirects for example. – Adders Mar 28 '23 at 18:38
Warning! chrome.tabs.getSelected
is deprecated. Please use chrome.tabs.query
as shown in the other answers.
First, you've to set the permissions for the API in manifest.json:
"permissions": [
"tabs"
]
And to store the URL :
chrome.tabs.getSelected(null,function(tab) {
var tablink = tab.url;
});
-
1The reason why its just for the popup (page action, browser action) is because your sending in a "null" into the first parameter. http://code.google.com/chrome/extensions/tabs.html#method-getSelected The docs state the first parameter is the windowId, if you want to use that in options, or background page, you would need to put in the window id or you will get the current tab your viewing which is undefined, options respectively. – Mohamed Mansour Dec 30 '09 at 17:06
-
1yes it works, but not sure why chrome.tabs.getSelected method can not be found in the reference document. – swimmingfisher Apr 25 '12 at 03:21
-
This thing is not working for me, `chrome.tabs.getSelected` is undefined, hould I ask it in a separate question? – Mostafa Shahverdy Mar 21 '13 at 10:38
-
14The `chrome.tabs.getSelected` method has been deprecated, the correct method is listed at [this below answer](http://stackoverflow.com/questions/1979583/how-can-i-get-the-url-for-a-google-chrome-tab/14251218#14251218). – Rob W Jun 29 '13 at 12:42
-
i put the "tabs" in the permissions in json file but this solution gets the URL "chrome://extensions/" although i'm on this page.... did i miss something ? – Tarek Jul 20 '13 at 08:51
-
1
-
-
This solution will fail if you try it using the website https://www.bloomberg.com where the url in Chrome updates as the user scrolls. – Johann Jul 25 '17 at 10:09
-
tabs is no longer a permission https://developer.chrome.com/apps/declare_permissions – sdfsdf Nov 11 '17 at 22:56
Other answers assume you want to know it from a popup or background script.
In case you want to know the current URL from a content script, the standard JS way applies:
window.location.toString()
You can use properties of window.location
to access individual parts of the URL, such as host, protocol or path.

- 74,770
- 16
- 179
- 206
-
1Great answer. All I wanted was `window.location.host` to see if Im at "stackoverflow.com" or not. – Salyangoz Sep 07 '17 at 06:10
-
4This is actually what I was looking for. I was so caught up in the extension mechanics that I forgot you can just grab the page's URL with window.location.href. – felwithe Mar 25 '18 at 02:51
-
This requires `match:"
"` situation on content_script section and Chrome is not reccomend – mcan Nov 07 '18 at 14:04. -
1@Tahtakafa No, it does not. It assumes a content script is already running (be it through a host permission for that page or activeTab). – Xan Nov 07 '18 at 14:05
-
1Make sure to run this in `contentScript.js` and not in the `background.js`. Just pass any data you've filtered from the URL into the message to `background.js`. Example: `let message = { type: "fetchVideoDate", id: getVideoId() };` where `getVideoId()` contains an execution of `window.location.toString()`. Otherwise you'll get some `chrome://temp_background_file.html` data. Also note that sometimes `message` is called `request`. – DavidHulsman Apr 28 '19 at 22:06
-
this will not work properly on Firefox if content.js is run on a page that contains iframes. I don't know if this is normal or it's a Firefox bug. – crisc2000 Nov 07 '19 at 17:59
-
after a few tests I found out why this method is not working properly on pages that have iframes. my manifest had "content_scripts": "all_frames" set to "true". I set it to "false", and now it's working properly. – crisc2000 Nov 07 '19 at 18:35
-
The problem is that chrome.tabs.getSelected is asynchronous. This code below will generally not work as expected. The value of 'tablink' will still be undefined when it is written to the console because getSelected has not yet invoked the callback that resets the value:
var tablink;
chrome.tabs.getSelected(null,function(tab) {
tablink = tab.url;
});
console.log(tablink);
The solution is to wrap the code where you will be using the value in a function and have that invoked by getSelected. In this way you are guaranteed to always have a value set, because your code will have to wait for the value to be provided before it is executed.
Try something like:
chrome.tabs.getSelected(null, function(tab) {
myFunction(tab.url);
});
function myFunction(tablink) {
// do stuff here
console.log(tablink);
}

- 65,848
- 11
- 132
- 136

- 281
- 3
- 2
-
Thanks for the code, this worked for me, "tabs" needs to be added to permissions in the manifest.json file "permissions": [ "tabs" ] – Doug Molineux Apr 13 '11 at 15:45
-
Also this works like a charm: [Getting current window on a popup (google chrome extension)](http://stackoverflow.com/questions/3030738/getting-current-window-on-a-popup-google-chrome-extension) – chemark May 30 '13 at 23:29
-
-
2
This is a pretty simple way
window.location.toString();
You probaly have to do this is the content script because it has all the functions that a js file on a wepage can have and more.

- 41
- 2
Hi here is an Google Chrome Sample which emails the current Site to an friend. The Basic idea behind is what you want...first of all it fetches the content of the page (not interessting for you)...afterwards it gets the URL (<-- good part)
Additionally it is a nice working code example, which i prefer motstly over reading Documents.
Can be found here: Email this page

- 2,059
- 2
- 18
- 31
This Solution is already TESTED.
set permissions for API in manifest.json
"permissions": [ ...
"tabs",
"activeTab",
"<all_urls>"
]
On first load call function. https://developer.chrome.com/extensions/tabs#event-onActivated
chrome.tabs.onActivated.addListener((activeInfo) => {
sendCurrentUrl()
})
On change call function. https://developer.chrome.com/extensions/tabs#event-onSelectionChanged
chrome.tabs.onSelectionChanged.addListener(() => {
sendCurrentUrl()
})
the function to get the URL
function sendCurrentUrl() {
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url
console.log(tablink)
})

- 1,130
- 2
- 12
- 22
async function getCurrentTabUrl () {
const tabs = await chrome.tabs.query({ active: true })
return tabs[0].url
}
You'll need to add "permissions": ["tabs"]
in your manifest.

- 12,272
- 14
- 80
- 106
For those using the context menu api
, the docs are not immediately clear on how to obtain tab information.
chrome.contextMenus.onClicked.addListener(function(info, tab) {
console.log(info);
return console.log(tab);
});

- 33,652
- 11
- 120
- 99
You have to check on this.
HTML
<button id="saveActionId"> Save </button>
manifest.json
"permissions": [
"activeTab",
"tabs"
]
JavaScript
The below code will save all the urls of active window into JSON object as part of button click.
var saveActionButton = document.getElementById('saveActionId');
saveActionButton.addEventListener('click', function() {
myArray = [];
chrome.tabs.query({"currentWindow": true}, //{"windowId": targetWindow.id, "index": tabPosition});
function (array_of_Tabs) { //Tab tab
arrayLength = array_of_Tabs.length;
//alert(arrayLength);
for (var i = 0; i < arrayLength; i++) {
myArray.push(array_of_Tabs[i].url);
}
obj = JSON.parse(JSON.stringify(myArray));
});
}, false);

- 18,766
- 20
- 94
- 101
-
My chrome extension for saving URL's on active windows is https://chrome.google.com/webstore/detail/tabstore-plugin/jngplpdonggccbjlmbphlbancacmpmpp – Kanagavelu Sugumar Oct 08 '15 at 04:49
If you want the full extension that store the URLs that opened or seen by the use via chrome extension:
use this option in your background:
openOptionsPage = function (hash) {
chrome.tabs.query({ url: options_url }, function (tabs) {
if (tabs.length > 0) {
chrome.tabs.update(
tabs[0].id,
{ active: true, highlighted: true, currentWindow: true },
function (current_tab) {
chrome.windows.update(current_tab.windowId, { focused: true });
}
);
} else {
window.addEventListener(hash, function () {
//url hash # has changed
console.log(" //url hash # has changed 3");
});
chrome.tabs.create({
url: hash !== undefined ? options_url + "#" + hash : options_url,
});
}
});
};
you need index.html file also. which you can find in the this Github the manifest file should be like this:
{
"manifest_version": 2,
"name": "ind count the Open Tabs in browser ",
"version": "0.3.2",
"description": "Show open tabs",
"homepage_url": "https://github.com/sylouuu/chrome-open-tabs",
"browser_action": {},
"content_security_policy": "script-src 'self' https://ajax.googleapis.com https://www.google-analytics.com; object-src 'self'",
"options_page": "options.html",
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"web_accessible_resources": ["img/*.png"],
"permissions": ["tabs", "storage"]
}
The full version of simple app can be found here on this Github:
https://github.com/Farbod29/extract-and-find-the-new-tab-from-the-browser-with-chrome-extention

- 990
- 1
- 10
- 20