0

For my Google Chrome extension, I need to grab the current URL. I know that, in regular JavaScript, I can just use this to get the link and host:

var hostname = window.location.hostname;
var url = window.location.href;

But how can I do that within an extension? I actually got it to work by using this as an example, but it seems a bit overkill for what I want to do. Is there a better way to get the current URL, maybe without injecting a script into the page?

noClue
  • 958
  • 1
  • 13
  • 34

1 Answers1

1

You can use chrome.tabs.query() to get the current URL into a variable inside your extension code:

chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function(tabs) {
    var url = tabs[0].url;
});

Remember: the part of your code that'll use the url variable should be inside the (anonymous) callback function above, not elsewhere. Otherwise, you'll get an undefined value, as Chrome extension code is executed asynchronously.

Achraf Almouloudi
  • 756
  • 10
  • 27
  • Awesome! One question, is there a way to pull the hostname from the tab, too? I got around it by grabbing the url and using 'new URL()' to turn it into an actual url that comes with a hostname, but maybe there is an easier option. – noClue Mar 27 '19 at 01:15
  • 1
    Using `URL()` is now the standard way to deal with URLs across most modern browsers (not just for Chrome extensions) so in your case `var hostname = new URL(tabs[0].url).hostname;` instead should give you the hostname only. – Achraf Almouloudi Apr 05 '19 at 20:45