使用 Javascript/Typescript 防止 html 注入

Prevent html Injections with Javascript/Typescript

所以我有一个简单的应用程序,用户可以在其中将 URL 插入到 iframe window 中。问题是这允许 html 注入,这会搞砸显示。

有没有简单的方法可以防止这种情况发生?比如正则表达式转义函数等?

TS/JS iframe 代码 window:

public renderPlot(): void {
    let ht: string = '';

    let url: string = this.configPBg[EConfigPKeys.IFrameAddress];

    if (url == undefined || url.length === 0) {
        this.renderWarningMessage('No valid address configured');
        return;
    }

    // auto stream with url like this : https://www.youtube.com/embed/jdnhfg?&autoplay=1&mute=1
    ht += '<iframe width="' + this.chartWindowSize.width + '" height="' + this.chartWindowSize.plotHeight + '" ';
    ht += 'src="' + url + '" ';
    ht += 'frameborder="0" ';
    ht += '>';
    ht += '</iframe>';

我尝试添加这个但没有捕捉到任何东西:

url.replace(/</g, "&lt;").replace(/>/g, "&gt;");

URL 报名表如下所示:

我将从 URL 变量中删除 all html:

url = url.replace( /<(?:(?:(?:(script|style|object|embed|applet|noframes|noscript|noembed)(?:\s+(?:"[\S\s]*?"|'[\S\s]*?'|(?:(?!\/>)[^>])?)+)?\s*>)[\S\s]*?<\/\s*(?=>))|(?:\/?[\w:]+\s*\/?)|(?:[\w:]+\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)+\s*\/?)|\?[\S\s]*?\?|(?:!(?:(?:DOCTYPE[\S\s]*?)|(?:\[CDATA\[[\S\s]*?\]\])|(?:--[\S\s]*?--)|(?:ATTLIST[\S\s]*?)|(?:ENTITY[\S\s]*?)|(?:ELEMENT[\S\s]*?))))>/g,
             "");

https://regex101.com/r/qwEyED/1

然后对 URL 进行验证:

var patURL = /^(?!mailto:)(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?:(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))|localhost)(?::\d{2,5})?(?:\/[^\s]*)?$/;

var res = patURL.test( url );
if ( res != true )
    // bad url