我实际上正在尝试确保 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/