273

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?

0

11 Answers 11

330

Use chrome.tabs.query.

ManifestV3:

(async () => {
  // see the note below on how to choose currentWindow or lastFocusedWindow
  const [tab] = await chrome.tabs.query({active: true, lastFocusedWindow: true});
  console.log(tab.url);
  // ..........
})();

ManifestV2/V3:

// see the note below on how to choose currentWindow or lastFocusedWindow
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.

"Current tab" definitions depends on your needs:

  • currentWindow: true always uses the window where your popup was initially shown regardless of whether the user has switched to another window after opening the popup. There's usually no difference at the start of the popup script, because it runs while the original window is still focused. The term currentWindow means "currently running extension code's window".

  • lastFocusedWindow: true uses the actually focused window at the time of the call (typically the topmost window), which may differ from the original window showing the popup in case the user has switched to another window (or your extension opened a new window) and chrome.tabs.query is called after that e.g. in a click listener for a button in the popup.

  • A chrome.runtime.onMessage listener should normally use sender.tab from the sender parameter.

9
  • 41
    Why is the url always undefined?
    – nnm
    May 31, 2014 at 12:27
  • 8
    If url is undefined try reloading your extension from chrome://extensions This will reload the extension's config and apply the newly added "tabs" permission. Apr 16, 2016 at 23:34
  • 7
    url is undefined because stackoverflow.com/questions/28786723/… (answer: close your dev tools window or change to currentWindow instead of lastFocusedWindow)
    – kspearrin
    Sep 14, 2016 at 3:01
  • 2
    I got undefined when my dev tools window was undocked. Docking it fixed the undefined issue.
    – Fisu
    Mar 6, 2018 at 13:30
  • 1
    This 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? Mar 11, 2020 at 9:51
95

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.

8
  • 1
    Great answer. All I wanted was window.location.host to see if Im at "stackoverflow.com" or not.
    – Salyangoz
    Sep 7, 2017 at 6:10
  • 4
    This 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, 2018 at 2:51
  • This requires match:"<all_urls>" situation on content_script section and Chrome is not reccomend <all_urls>.
    – mcan
    Nov 7, 2018 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 7, 2018 at 14:05
  • 1
    Make 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. Apr 28, 2019 at 22:06
91

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;
});
9
  • 1
    The reason why its just for the popup (page action, browser action) is because your sending in a "null" into the first parameter. 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. Dec 30, 2009 at 17:06
  • 1
    yes it works, but not sure why chrome.tabs.getSelected method can not be found in the reference document. Apr 25, 2012 at 3:21
  • This thing is not working for me, chrome.tabs.getSelected is undefined, hould I ask it in a separate question? Mar 21, 2013 at 10:38
  • 14
    The chrome.tabs.getSelected method has been deprecated, the correct method is listed at this below answer.
    – Rob W
    Jun 29, 2013 at 12:42
  • 1
    And, how to get links of all open tabs
    – Idrizi.A
    Jul 27, 2013 at 18:05
28

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);
}
4
  • Thanks for the code, this worked for me, "tabs" needs to be added to permissions in the manifest.json file "permissions": [ "tabs" ] Apr 13, 2011 at 15:45
  • Also this works like a charm: Getting current window on a popup (google chrome extension)
    – chemark
    May 30, 2013 at 23:29
  • And, how to get links of all open tabs
    – Idrizi.A
    Jul 27, 2013 at 18:04
  • 2
    i tried this but getting url undefined why is this?
    – nnm
    May 31, 2014 at 12:27
4

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.

1
  • 1
    You can also use this with js in wepages.
    – unixGeek
    Jul 29, 2021 at 22:17
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

1

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

0

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

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

-2

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);
1
-3

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"]
}

All unique seen URL stored in an array depicted in browser console

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.