javascripthtmlrequest.servervariables

Assign <!--#echo var=REQUEST_URI --> to JS variable


This may be somewhat of an obvious question - but how can I use the code I already have in the head of my HTML doc:

<link rel="alternate" hreflang="en" href="https://www.example.com
<!--#echo var=REQUEST_URI -->" />

To get the page URL and assign this to a JS variable? I'd like to abstain from using JS to get the URL itself.

Many thanks in advance!


Solution

  • AFAIK, there isn't a good way to do this with simple SSI.

    A naïve approach would be:

    <script>
        var uri = "<!--#echo var=REQUEST_URI -->";
    </script>
    

    but this would render you vulnerable to XSS attacks.

    You could use EXEC to run a CGI program that gets the URI, sanitises it and then outputs it, but that would be inefficient.

    You might want to abstain from JS for getting the URL, but:

    <script>
        var uri = location.href;
    </script>
    

    is almost certainly the easiest, most reliable, and fastest solution. It doesn't even add an unnecessary dependance on JS (which is my usual objection to this sort of thing) since you are getting the data for the express purpose of passing it to JS.