删除 C# 中的所有内联 Javascript答案

作者: 分类: 编程代码 时间:1970-01-01

删除 C# 中的所有内联 Javascript答案

Remove all Inline Javascript in C#删除 C# 中的所有内联 Javascript

我有一个字符串: `<p onclick="alert('abc')" style="color: black">text</p>`

我想删除所有像 onclick, onchange, ... 这样的 Javascript,只留下 HTML 和 CSS。有没有办法在 C# 中做到这一点?我能想到的唯一方法是从字符串中删除每个 javascript 标记。

输入:<p onclick="alert('abc')" style="color: black">text</p>

输出:<p style="color: black ">text</p>

【问题讨论】:

标签: javascript c# string


【解决方案1】:

您可以使用HtmlSanitizer 删除提供的 HTML 片段的内联 java 脚本。

例如 - 以下代码

var sanitizer = new HtmlSanitizer();
var html = @"<script>alert('xss')</script><div onload=""alert('xss')"""
    + @"style=""background-color: test"">Test<img src=""test.gif"""
    + @"style=""background-image: url(javascript:alert('xss')); margin: 10px""><p onclick =""alert('abc')"" style =""color: black"">text</p></div>";
var sanitized = sanitizer.Sanitize(html);

将输出返回为

<div>Test<img src="test.gif" style="margin: 10px"><p style="color: rgba(0, 0, 0, 1)">text</p></div>

您可以查看thisfiddle 了解更多详情。

【讨论】:

    【解决方案2】:

    ***的方法是使用Html Agility Pack。我已在其文档中链接了您需要的页面。

    像这样使用它:

    var htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(html);
    var pNode = htmlDoc.DocumentNode.SelectSingleNode("//p");   
    pNode.Attributes.Remove("onclick");
    

    Here 是小提琴。

    【讨论】: