Is Javascript/jQuery DOM creation safe until it's added to the document?

前端 未结 4 1894
半阙折子戏
半阙折子戏 2021-01-31 16:49

Please read this statement carefully: let\'s assume before ANY elements are added to the document all unsafe elements in $dom have

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-31 17:47

    Is this by itself dangerous in any way? My point being, can just the simple act of creating a DOM somehow inject anything, or is it just simply processed and the structure is created?

    Simply creating an element without appending it to the dom will not cause any script to run since it is purely an object at this point (HtmlScriptElement). When it is actually appended to the dom the script element will be evaluated and ran by the browser. With that being said I suppose it is possible that an extremely crafty person could exploit a bug that is present in some framework or browser you might be using to cause an undesired outcome.

    Consider this example:


    The Script

        $(function(){
            function clickIt(){
                $(this).clone().click(clickIt).appendTo("body");
            }
            $("input[type='button']").val("Now Does Something").click(clickIt);
        });
    
    var theScript; $("#store").click(function() { theScript = document.createElement('script'); var scriptText = document.createTextNode($("#script").text()); theScript.appendChild(scriptText); }); $("#append").click(function() { var head = document.getElementsByTagName('head')[0]; head.appendChild(theScript); });

    When you click on store it will create the HtmlScriptElement and store it into a variable. You will notice that nothing is ran even though the object is created. As soon as you click append the script is appended to the dom and immediately evaluated and the buttons do something different.

    Code Example on jsfiddle


    Can any functions in javascript/jquery "watch" for elements being created in this manner and act on it BEFORE it's been stripped of bad elements and put on document?

    jQuery sort of does that for you already as it does some internal script eval


    From Karl Swedberg post on .append()

    All of jQuery's insertion methods use a domManip function internally to clean/process elements before and after they are inserted into the DOM. One of the things the domManip function does is pull out any script elements about to be inserted and run them through an "evalScript routine" rather than inject them with the rest of the DOM fragment. It inserts the scripts separately, evaluates them, and then removes them from the DOM. ...

    You could alter the behavior of jQuery to remove all

提交回复
热议问题