Search code examples
javascripthtmlhref

Insert string from <script> into to <a href="">


I have the following script:

<script>var b=document;var c=varName;b.write(c);</script>

and I want to pass the value from the <script> tag to the name URL parameter in a link, in place of the * here:

`<a href="whatsapp://send?text='Hello This is My Demo Site. Visit http://example.com/ex.html?name=ABC*'"> WhatsApp </a>`

My attempt resulted in getting the whole script string:

<a href="whatsapp://send?text='Hello This is My Demo Site. Visit http://example.com/ex.html?name=ABC<script>var b=document;var c=varName;b.write(c);</script>'"> WhatsApp </a>


Solution

  • No, you cannot insert scripts within an HTML attribute. You must compose the complete HTML first:

    <a id="caption" href="whatsapp://send?text=Hello This is My Demo Site. Visit http://example.com/ex.html">link text</a>
    

    ... And then, you can modify it from javascript:

    <script>
        var a = document.getElementById("caption");
        var question = "%3F";
        var equal = "%3D";
        a.href += question + "name" + equal + "ABC" + lusername;
    </script>
    

    Note that I did intentionally escape "?" and "=" when forming the parameters, because I understand they are arguments for the http://www.example.com URL and not for the whatsapp://send URL.