Search code examples
javascriptgoogle-chrome-extensionwebrequest

Chrome Ext: Javascript interrogate URL string for hostname


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?


Solution

  • 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
    }