views:

89

answers:

2

Using the Google Chrome API 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? Thanks in advance!

function show_alert()
 {
        chrome.tabs.getSelected(null, function(tab) {
            var currentURL = tab.url;
                        alert(currentURL);
        });

 }
+1  A: 

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-]+:\/*\[?([\w\.:-]+)\]?(?::\d+)?/)[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-]+:\/*\[?([\w\.:-]+)\]?(?::\d+)?/)[0];
// Given uri = "http://www.google.com/", origin == "http://www.google.com"
Eli Grey
+1  A: 

If you are using jQuery there is a URL parsing plugin that can split provided url into pieces.

serg
src0010