Append html to jQuery element without running scripts inside the html

后端 未结 2 2045
别跟我提以往
别跟我提以往 2021-02-02 15:46

I have written some code that takes a string of html and cleans away any ugly HTML from it using jQuery (see an early prototype in this SO question). It works pretty well, but I

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-02 16:51

    How about removing the scripts first?

    var wrapper = $('
    ').append($(html).not('script'));

    • Create the div container
    • Use plain JS to put html into div
    • Remove all script elements in the div

    Assuming script elements in the html are not nested in other elements:

    var wrapper = document.createElement('div');
    wrapper.innerHTML = html;
    $(wrapper).children().remove('script');
    

    var wrapper = document.createElement('div');
    wrapper.innerHTML = html;
    $(wrapper).find('script').remove();
    

    This works for the case where html is just text and where html has text outside any elements.

提交回复
热议问题