Search code examples
htmlhyperlinkhref

HTML link to either local network or domain name


In my web page, I want to link to another web server in my local network. I use <a href="192.168.1.111:8080/index.jsp">to do this when I am in local network. However, when I access the website outside the local network, I need to use domain name. <a href="mydomain.com:8080/index.jsp">

How can I do this in same page of code if I would access it from both LAN and WAN.


Solution

  • Well, if it's an option, the easiest way to avoid this issue is using relative links. For example, if you're linking to another page on the same website, your link will always work if it's something like "../directory/some-web-page.html" rather than a full link with http included.

    Otherwise, if you're linking to a completely different site, you could check whether your page exists on the local server using a very simple JQuery ajax request. If it doesn't exist, then assume you are not signed in to the same network and insert your remote domain name.

    As discussed here, your simple ajax request can just fetch the HEAD of the locally hosted page, that way you're not fetching too much data and only confirming whether it exists. Your code could be something like this:

    $( document ).ready(function(){
        $.ajax({
            url: 'path/to/your-file.html',
            type: 'HEAD',
            success: function() {
                // page exists
                // replace the href attribute with local host link
                document.getElementById('your-link').setAttribute('href', 'path/to/your-file.html');
            },
            error: function() {
                // page does not exist
                // do nothing, so your link sends user to remote site
            }
        });
    
    });
    

    And then, in your HTML, just include the link to your remote site like so:

    <a id="your-link" href="yourremotesite.com">This is a link</a>
    

    This should work on both a local and remote server without having to change the code.

    EDIT:

    I had to jump out of bed because another answer was just nagging at me...

    You can also try accessing window.location.host or window.location.hostname and testing that in an if-statement to determine whether your page is on the local host or remote server.

    Anyway, I hope one of these solutions helps. Good night and good luck!