0

I have an url http://www.example.com/folder/file.html. I want to get domain (example.com) and path (example.com/folder/) of the current url.

Using

chrome.tabs.onUpdated.addListener(function(tabid, changeInfo, tab){
    chrome.tabs.query({'active' : true, 'currentWindow': true}, function(tabs){
        let newUrl = new URL(tabs[0].url);
        currentDomain = newUrl.hostname;
});

leads me to getting the host - www.example.com instead of example.com.

Evgeniy
  • 2,337
  • 2
  • 28
  • 68

1 Answers1

0

www is just like any other subdomain, so JS can't know if it's part of the domain or not. But you can remove the www manually:

currentDomain = newUrl.hostname.replace(/^www\./, "");

to get the path, use pathname:

const currentPath = `${currentDomain}/${newUrl.pathname}`
Vlad Gincher
  • 1,052
  • 11
  • 20
  • Hmm, i need the pure domain - without any subdomain, not only www. Is there a way to get only domain? – Evgeniy Feb 08 '20 at 20:02
  • That's more complicated, as you can't know how many 'parts' there are in the domain itself. It can be example.com, and it can be example.co.uk and can be www.yt.be. You can use the solutions suggested here: https://stackoverflow.com/questions/9752963/get-domain-name-without-subdomains-using-javascript – Vlad Gincher Feb 08 '20 at 20:12
  • `pathname` gets `/folder/index.html` - but i need only `/folder/`. Is this achievable? – Evgeniy Feb 11 '20 at 02:16