Search code examples
aem

How to get the website domain name in a component's jsp/html in aem?


I need to get the domain name of the website in my component's jsp/html using sightly.

Lets say if the page url is "https://test.com/en.html", I just need to get "https://test.com". How can I achieve it without using any java code?

Is there any direct method that I can use?


Solution

  • Server Side

    If you want to get the domain name on the server side (i.e. have it show up in the rendered HTML which is sent in the initial response).

    One of the global objects available to use in HTL (formerly known as sightly) is the request object. This object is a SlingHttpServletRequest, so you should be able to use the serverName property. (I believe this object is also available in JSPs if use the <cq:defineObjects> described here)

    ${request.serverName}
    

    Client Side

    If you want to get the domain name on the client (i.e. in the browser of the person loading the page).

    You can use the normal window.location object in Javascript to get the hostname:

    <script>
        let domainName = window.location.hostname;
        //do the JS stuff you want to with the domain name
    </script>
    

    Check the Location docs for all the available properties of window.location.