0

I'm writing a javascript code that update DOM with html/javascript from XMLlHttpRequest response (A sort of JQuery's $.load() function), depending on some client side condition (e.g. which browser user is using).

I put this function in a separate javascript file (linked in page with <script> tag) and pass url as arguments. Function is invoked from an inline <script> tag and url is passed as a string literal (does not come from request parameter or session attributes):

xhr-library.js

var MyClass = function(args){
    
    MyClass.prototype.init = function(){
       
       var xhr = new XMLHttpRequest();
       xhr.addEventListener('load',function(){

            // Since script and html block, from xhr response, 
            // need to be injected in different sections, i need to
            // parse xhr response...
            var objElement = document.createElement('div');
            objElement.innerHTML = (xhr.response || xhr.responseText);

            // ...and extract script and html as a separate childs...
            var myhtml = objElement.children[1];
            var myscript = document.createElement('script');
            myscript.innerHTML = objElement.children[0].innerHTML;

            // Html block is appended as first child of <body> tag
            document.body.insertBefore(myhtml, document.body.firstChild);

            // Script block is appended as last child of <head> tag
            document.head.appendChild(myscript);

       });
       
       xhr.open("GET", args.url, false);
       xhr.send();

    }

}

page.html

<script type="text/javascript" src="${pageContext.request.contextPath}/js/xhr-library.js"></script>
<script type="text/javascript">

        var xhrLib;

        document.addEventListener('DOMContentLoaded', function(){

            xhrLib = new MyClass({
                url : 'GetTemplate.action'
            });

            xhrLib.init();

        }, false);

    </script>

assuming that injected code does not contains security issues, is, this code, exposed to some kind of XSS attack? Is this code safe? How can I improve this code from security point of view?

I apologize in advance for my English or my poor explanation.

1
  • Your code leaves the dynamically inserted code with access to the global namespace. Instead of creating an HTML element, which is quite hacky, why not try the new Function() method (javascript.info/new-function) which is similar to eval(), but doesn't expose the global namespace? Jun 24 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.