HTML Javascript - Prevent script execution from child nodes of a dom tree

随声附和 提交于 2020-01-15 05:20:07

问题


I download some html tree from an untrustworthy source, and use it to just display content as a child of some HTML div in my page. However, there is the danger of this downloaded code running scripts/or executing scripts in event handlers. Is it possible in HTML just like using a tag to define scripts, do a

<noscriptex>
    <script>
        ...
    </script>
</noscriptex>

then the browser wouldn't execute any code within this tag?

If there is no such thing, how do I clean up the downloaded HTML just to display DOM elements with their CSS without any scripting involved?


回答1:


No; there is no such feature.

Instead, you need to parse the HTML and remove any unrecognized tags and attributes using a strict whitelist.

You also need to validate attribute values; especially URLs.




回答2:


You can use a function to remove scripts from markup, e.g.

function stripScripts(markup) {

    var div = document.createElement('div');
    var frag = document.createDocumentFragment();

    div.innerHTML = markup;

    var scripts = div.getElementsByTagName('script');
    var i = scripts.length;

    while (i--) {
      scripts[i].parentNode.removeChild(scripts[i]);
    }

    while (div.firstChild) {
      frag.appendChild(div.firstChild);
    }
    return frag;
}

Any script elements inserted using innerHTML are not executed, so they're safe. They aren't in the DOM yet either so have limited power.

Note that the object returned by createDocumentFragment can be inserted directly into the DOM, and the fragment returned by the function has no script elements.




回答3:


This is what an iframe is for. If the content comes from a different domain than the host page, then it will not be allowed to communicate with any of the other content. You can let it run scripts to its heart's content and they can't affect your part of the page.



来源:https://stackoverflow.com/questions/12488339/html-javascript-prevent-script-execution-from-child-nodes-of-a-dom-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!