Search code examples
htmliframeserver

Get current directory address as localhost


This is continuation of question asked here (Provide link to iframe via js) as a second part. Here I am opening my iframe link. The iframe link opens up a PDF. I am currently running the code in localhost server which is why the address is http://127.0.0.1:5500. But when I upload it to the main server, this will be changed. My question is, since the link of the PDF is stored in the same directory as the index.html page. How do I automatically generate http://127.0.0.1:5500 or any other address depending on the hosting server. Such that it could be www.myhostingserver.come/myID/PDFIni.pdf and I do not have to manually enter the hosting address, rather just give : hostingaddress+"/PDFIni.pdf"?

<script>
...
...

let myIframe = document.getElementById("iframe");
        
        if(myIframe.src != "http://127.0.0.1:5500/PDFIni.pdf")
        {
            console.log(myIframe.src);
            myIframe.src = "http://127.0.0.1:5500/PDFIni.pdf";
        }

Solution

  • Try to use document.location.hostname. For example:

        var str = 'https://' + document.location.hostname + '/PDFIni.pdf';
        
        if(myIframe.src != str) {
            console.log(myIframe.src);
            myIframe.src = str;
        }