Search code examples
javascriptdomparameter-passingreplacesrc

updating a parameter within location (src) using JavaScript


How can I parse the value of status = 'logged-out' to the 3 tags below it, updating the value of login_status = 'logged-out'?

<script type="text/javascript">
      window.ndm = window.ndm || {};
      window.ndm.cam = {'status':'logged-out'};
</script>

<script src="http://foo.com/adserver/ndm/js.php?position=header-ad&amp;section_id=NEWS&amp;login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=middle-ad&amp;section_id=NEWS&amp;login_status=SUBSCRIBER"></script>
<script src="http://foo.com/adserver/ndm/js.php?position=footer-ad&amp;section_id=NEWS&amp;login_status=SUBSCRIBER"></script>

Keep in mind, there also heaps of other script tags on the page, so to identify the relevant ones. I got this function.

function getScriptSourceName(name){
var scripts = document.getElementsByTagName('script');
for (i=0;i<scripts.length;i++){
    if (scripts[i].src.indexOf(name) > -1)
        return scripts[i].src;
}}

Therefore to find the relevant script tags I want, i call the function - getScriptSourceName('foo.com');

How can I then update the login_status parameter's value to use the one declare at the very top?


Solution

  • I think this should work (below the HTML file for testing). Look at changeStatus method (I triggered it by button click for testing).

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <html>
    <head>
        <script type="text/javascript">
          window.ndm = window.ndm || {};
          window.ndm.cam = {'status':'logged-out'};
        </script>
    
        <script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
        <script src="http://foo.com/some.php?login_status=SUBSCRIBER"></script>
        <script src="http://foofoo01.com/some.php?login_status=SUBSCRIBER"></script>
    
        <script>
            function changeStatus(name)
            {
                var scripts = document.getElementsByTagName('script');
                var scriptsToChange = [];
                for (var i = 0; i < scripts.length; i++)
                {
                    if (scripts[i].src.indexOf(name) > -1)
                    {
                        var oldSrc = scripts[i].src;
                        var newSrc = oldSrc.replace(/(login_status=).*/,'$1' + 'logged-out');
                        scripts[i].setAttribute("src", newSrc);     
                        scriptsToChange.push(scripts[i]);               
                    }
                }
    
                for (var k = 0; k < scriptsToChange.length; k++)
                {
                    document.getElementsByTagName("head")[0].appendChild(scriptsToChange[k]);
                }
            }
        </script>
    </head>
    <body>      
        <button type="button" onclick="changeStatus('foo.com')">Change status</button>
    </body>
    </html>