Skip to content Skip to sidebar Skip to footer

Html Javascript - Prevent Script Execution From Child Nodes Of A Dom Tree

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 c

Solution 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.

Solution 2:

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

functionstripScripts(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.

Solution 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.

Post a Comment for "Html Javascript - Prevent Script Execution From Child Nodes Of A Dom Tree"