gpt4 book ai didi

javascript - 如何防止 html 元素转义父元素? (安全)

转载 作者:行者123 更新时间:2023-11-28 03:24:22 25 4
gpt4 key购买 nike

我尝试用 Google 搜索这个,但一切都与 css 有关,而不是安全性。

我将此作为评论表单:

<pre name="comment">
<comment-content>
This is a sample comment by a user
</comment-content>
</pre>

我允许一些受控的 html 标签,其中包括 [pre][/pre]这就是问题开始的地方。

如果我做这样的事情:

<pre name="comment">
<comment-content>
This is a sample comment by a user
[/pre]
This text will be outside the comment container
</comment-content>
</pre>

注释转义了 pre 标记,并忽略了它在 <comment-content></comment-content> 内的情况。标签。我添加此标签是为了尝试阻止转义,但它不起作用。我还注意到我的受控 html 标签将在容器外部运行。我有第二个未转义的容器,但是转义第一个容器的问题意味着如果我放置 <pre>标签在该容器之外,它可能会被转义。我也尝试过将容器加倍,但这也不起作用。

Here is an image of the [/pre] tag escaping the container

这里是 javascript 在后台执行的操作的快速示例:

//I added .cleanHTML() as a similar function to php htmlentities() and .clean() is similar to php strip_tags()
let content = $(this).html().cleanHTML().clean();

commentHtml += '<pre name="comment" type="text/plain"><comment-content>'+setUserCommentHtml(content.clean())+'</comment-content></pre>';

$(this).html(commentHtml);

注意:我知道大多数安全性应该在服务器端完成,但也希望确保客户端安全。

我基本上需要一种方法来强制 html 在第二个父结束标记起作用之前需要第一个结束标记。

最佳答案

发布解决方案(在评论的帮助下)作为答案以标记为已解决。

贾里德·法里什在评论中回答了问题。

将我的 javascript 更改为类似的内容可以解决问题:

//I added .cleanHTML() as a similar function to php htmlentities() and .clean() is similar to php strip_tags()
let content = $(this).html().cleanHTML().clean();

let setContentId = Math.floor(Math.random()*10000);
commentHtml += '<pre name="comment" type="text/plain"><comment-content set-content="'+setContentId+'"></comment-content></pre>';

$(this).html(commentHtml);

$('comment-content[set-content="'+setContentId+'"]').html(setUserCommentHtml(content.clean()));

我还在 setUserCommentHtml() 函数中添加了此方法。

let htmlOpenTags = [];

//in a loop
if(tagType === 'close' && htmlOpenTags.includes(commentTag)){
htmlOpenTags.splice(htmlOpenTags.lastIndexOf(commentTag));
//close tag here
...
}else if(tagType === 'open'){
htmlOpenTags.push(commentTag);
//open tag here
...
}

如果我推送到一个数组,每次用户打开一个标签时,我可以在关闭它之前验证打开的标签是否存在于该数组中,并从列表中删除该标签。

编辑:堆栈溢出表示我必须等待 2 天才能标记为答案

关于javascript - 如何防止 html 元素转义父元素? (安全),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58790232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com