一、原生dom方式
使用JavaScript原生dom替换append方法,原生dom会忽略<script>标签。比如,下列代码就会报Cross Site Scripting DOM攻击的问题
1 2 3 4 5 6 7 8 | <div id= "jqueryid" > </div> <script> $(document).ready( function (){ var val = "<script>console.log('cross site');" $( '#jqueryid' ).append(val); // console会打印出 cross site }); </script> |
修改方案为
1 2 3 4 5 6 7 8 | <div id= "jqueryid" > </div> <script> $(document).ready( function (){ var val = "<script>console.log('cross site');" $( '#jqueryid' )[0].innerHTML = val; // console不再会打印出cross site }); </script> |
在jQuery方法中,初append之外,html、before、after等方法同样存在此跨站点攻击的问题。
二、传入参数特殊处理
我们也可以将传入的参数进行特殊符号转化成html的方式处理。
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 | <div id= "jqueryid" > </div> <script> $(document).ready( function (){ var script = "<script>console.log('cross site');" $( '#jqueryid' ).append(encodeHtml(script)); // console不会打印出cross site function encodeHtml(value){ return $( '<div/>' ).text(value).html(); } }); </script> |
其实在jQuery的官方文档中,存在如下说明。正是解决跨站点攻击的方法所在。
This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.
Additional Notes: By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, <img onload="">). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?