How can I get the URL of the current tab from a Google Chrome extension?
Asked Answered
A

11

274

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?

Aldrich answered 30/12, 2009 at 10:55 Comment(0)
M
331

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.

Musser answered 10/1, 2013 at 5:13 Comment(9)
Why is the url always undefined?Vitrification
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.Mcconaghy
url is undefined because #28787223 (answer: close your dev tools window or change to currentWindow instead of lastFocusedWindow)Pentimento
I got undefined when my dev tools window was undocked. Docking it fixed the undefined issue.Altdorfer
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?Anastaciaanastas
@ThierryDalon You could use async/await I guess.Anamorphic
This answer sadly neglects to mention that you can't access the chrome.tabs area inside of a content script. See: https://mcmap.net/q/110490/-chrome-tabs-getcurrent-or-tabs-queryGymnosophist
This will give you the wrong urlPickard
How would you get the URL on the initial request? So before any redirects for example.Octodecillion
F
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.

Farquhar answered 20/7, 2016 at 12:43 Comment(8)
Great answer. All I wanted was window.location.host to see if Im at "stackoverflow.com" or not.Tummy
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.Danndanna
This requires match:"<all_urls>" situation on content_script section and Chrome is not reccomend <all_urls>.Bone
@Tahtakafa No, it does not. It assumes a content script is already running (be it through a host permission for that page or activeTab).Farquhar
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.Jamesy
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.Suggs
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.Suggs
upvoted for explaining why other answers ignore the standard wayMown
A
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;
});
Aldrich answered 30/12, 2009 at 11:31 Comment(9)
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.Zlatoust
yes it works, but not sure why chrome.tabs.getSelected method can not be found in the reference document.Haines
This thing is not working for me, chrome.tabs.getSelected is undefined, hould I ask it in a separate question?Devastating
The chrome.tabs.getSelected method has been deprecated, the correct method is listed at this below answer.Danaedanaher
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 ?Aneroid
And, how to get links of all open tabsPatman
I want to get current URL inside main.js , any guidance?Percuss
This solution will fail if you try it using the website bloomberg.com where the url in Chrome updates as the user scrolls.Levine
tabs is no longer a permission developer.chrome.com/apps/declare_permissionsLeung
C
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);
}
Cist answered 30/3, 2010 at 10:35 Comment(4)
Thanks for the code, this worked for me, "tabs" needs to be added to permissions in the manifest.json file "permissions": [ "tabs" ]Iroquois
Also this works like a charm: Getting current window on a popup (google chrome extension)Ebbarta
And, how to get links of all open tabsPatman
i tried this but getting url undefined why is this?Vitrification
M
3

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.

Misrule answered 29/7, 2021 at 22:17 Comment(1)
You can also use this with js in wepages.Misrule
R
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

Recapitulate answered 30/12, 2009 at 11:58 Comment(0)
S
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)
  })
Switzerland answered 15/6, 2020 at 6:41 Comment(0)
F
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.

Falsify answered 9/3, 2022 at 14:25 Comment(0)
A
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

Agog answered 16/11, 2014 at 19:38 Comment(0)
S
-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);
Spousal answered 8/10, 2015 at 4:47 Comment(1)
My chrome extension for saving URL's on active windows is chrome.google.com/webstore/detail/tabstore-plugin/…Spousal
A
-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

Achromic answered 12/11, 2021 at 23:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.