0

Note. This is not interrogate the url that you get from window.location

I am using the chrome.webRequest.onBeforeRequest.addListener which returns details. These details are:

{
    frameId: 0,
    method: "GET",
    parentFrameId: -1,
    requestId: "687379",
    tabId: 1721765993,
    timeStamp: 1543573944865.511,
    type: "main_frame",
    url: "https://stackoverflow.com"
}       

which means that the only URL I can get it from using details.url which is a string in the return. In this example it is:

url: "https://stackoverflow.com"

I want to be able to get the hostname only:

stackoverflow.com

The problem arises when there is https or http. If there is a subdomain or if there is extra paths.

How do I get only the hostname?

modusTollens
  • 397
  • 7
  • 23
  • Possible duplicate of [How do I parse a URL into hostname and path in javascript?](https://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript) – wOxxOm Nov 30 '18 at 10:55

1 Answers1

2

Here is a neat little trick I use:

function processUrl(url) {
    var a = document.createElement('a');
    a.href = url;
    return a.hostname;

}

and then pass in your details.url to that function.

This creates an element and the browser engine processes the a element and works out your hostname etc. So you can return a.hostname.

Edit

As mentioned below, this might be a little outdated. Another great solution is:

function processUrl(url) {
    return new URL(url).hostname
}
MarkP
  • 2,546
  • 5
  • 31
  • 48
  • @wOxxOm - Great reply :) Added it to the answer. And yeah a little outdated - I just kept using it because it worked haha. Thanks for the update to my knowledge :) – MarkP Nov 30 '18 at 10:59