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); }); }
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.
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.
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' })
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With