Join the Stack Overflow Community
Stack Overflow is a community of 6.5 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

Using the Google Chrome API's tab.url value, what is the best method to get just the domain from the entire value?

In JavaScript I would use window.location.protocol & window.location.hostname. For example something like this:

var domain = window.location.protocol + "//" + window.location.hostname;

But that gets the extension domain and not the tab so cannot use that method. So with a function similar to the one below... How would I strip just the domain from the tab.url value?

function show_alert() {
    chrome.tabs.getSelected(null, function(tab) {
        var currentURL = tab.url;
        alert(currentURL);
    });
}
share|improve this question

First of all, domains don't include a protocol. I have created a regular expression for your problem. To get the hostname (you'd want to do this as IP addresses are not domains) of a URI, use the the following:

var domain = uri.match(/^[\w-]+:\/{2,}\[?([\w\.:-]+)\]?(?::[0-9]*)?/)[1];
// Given uri = "http://www.google.com/", domain == "www.google.com"

If you want the origin (protocol + host (not hostname, there's a difference) + optional port) instead of the domain, use the following:

var origin = uri.match(/^[\w-]+:\/{2,}\[?[\w\.:-]+\]?(?::[0-9]*)?/)[0];
// Given uri = "http://www.google.com/", origin == "http://www.google.com"
share|improve this answer
2  
Just brilliant. – miksiii Jan 22 '15 at 0:06

Since this question was originally answered, a better solution has appeared.

Most modern browsers now support use of the URL constructor, which provides access to href, hostname, path and all standard ways of splitting up a URL.

To get the domain, you could do the following:

chrome.tabs.getSelected(null, function (tab) {
  var url = new URL(tab.url)
  var domain = url.hostname
  // `domain` now has a value like 'example.com'
})
share|improve this answer
3  
This should be the accepted answer. Just say no to crazy regexes! :-) – Perry Aug 26 at 23:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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