Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Chrome Plugin: How to get domain from URL (tab.url)

Tags:

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);     }); } 
like image 886
OtoNoOto Avatar asked Sep 11 '10 01:09

OtoNoOto


People also ask

How do I find the URL of a Chrome tab?

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.

How do I find a URL extension?

It's as simple as Right Click > getURL. Open up the Extension popup window and you will be greeted with the parameters in a nicely formatted table.


2 Answers

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.query({ active: true, currentWindow: true }, function (tabs) {   var tab = tabs[0];   var url = new URL(tab.url)   var domain = url.hostname   // `domain` now has a value like 'example.com' }) 
like image 131
Ross Zurowski Avatar answered Oct 26 '22 04:10

Ross Zurowski


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" 
like image 38
Eli Grey Avatar answered Oct 26 '22 06:10

Eli Grey