regex - 查找所有 DOM 事件监听器的正则表达式

标签 regex security wysihtml5

我实际上正在尝试确保 wysihtml5 编辑器的结果安全。
基本上,用户无法输入脚本/表单/等标签。

我无法删除所有标签,因为其中一些标签用于根据需要显示内容。
(例如:<h1> 显示标题)

问题在于用户仍然能够添加绑定(bind)到某些不需要的代码的 DOM 事件监听器。
(例如:<h1 onclick="alert('Houston, got a problem');"></h1>)

我想删除 div 内的所有事件监听器(对于该 div 内的所有后代)。
我实际尝试使用的解决方案是将代码作为字符串进行检查,以查找和替换不需要的内容,这适用于不需要的标签。

我真正需要的是一个匹配所有标签内的所有事件监听器的正则表达式。
类似于“选择 < 和 > 之间的所有 [on*]”。
例子:
<h1 onclick=""></h1> => 应该匹配
<h1 onnewevent=""></h1> => 应该匹配
<h1>onclick=""</h1> => 应该匹配

预先感谢您的帮助;)

最佳答案

不应使用正则表达式解析 html。
如果你真的想这样做,这是一种快速而肮脏的方式
(绝不完整)。

它只是查找开始“oneevent”标记及其后面的结束标记。
如果中间还有其他内容,只需在标签之间添加 .*? 即可。

 #  <([^<>\s]+)\s[^<>]*on[^<>="]+=[^<>]*></\1\s*>
 # /<([^<>\s]+)\s[^<>]*on[^<>="]+=[^<>]*><\/\1\s*>/

 < 
 ( [^<>\s]+ )                    # (1), 'Tag'
 \s 
 [^<>]* on [^<>="]+ = [^<>]*     # On... = event
 >
 </ \1 \s* >                     # Backref to 'Tag'

Perl 测试用例

$/ = undef;

$str = <DATA>;

while ( $str =~ /<([^<>\s]+)\s[^<>]*on[^<>="]+=[^<>]*><\/\1\s*>/g )
{
    print "'$&'\n";
}


__DATA__
(eg : <h1 onclick="alert('Houston, got a problem');"></h1>) 

I would like to remove all event listeners inside a div
(for all descendants inside that div).
The solution I actually tried to use is to check the code as
a string to find and replace unwanted content,
which worked for the unwanted tags. 

What I actually need is a regex matching all event
listeners inside all tags.
Something like "select all [on*] between < and >".
Examples :
<h1 onclick=""></h1> => Should match
<h1 onnewevent=""></h1> => Should match
<h1>onclick=""</h1> => Should NOT match 

输出>>

'<h1 onclick="alert('Houston, got a problem');"></h1>'
'<h1 onclick=""></h1>'
'<h1 onnewevent=""></h1>'

关于regex - 查找所有 DOM 事件监听器的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22484987/

相关文章:

javascript - 使用javascript中的正则表达式从文本中过滤掉数字

c# - IDX10503 : Signature validation failed. token 没有 child 。尝试的 key : 'System.Text.StringBuilder'

docker - Owasp zap 中基于 header 的身份验证

javascript - 颜色、插入链接和插入图像弹出窗口未在 wysihtml5 中显示

javascript - bootstrap 3-所见即所得编辑器对象始终未定义

javascript - wysihtml5 光标跳到新行的错误位置

JavaScript,简单 : make global

regex - IIS URL 重写,URL 中的条件更改

javascript - 除非转义,否则 RegEx 不允许字符

security - 同步 CRM 2011 和 SharePoint 安全性