使用jQuery.append()、jQuery.html()方法時,如果其中內容包含<script>腳本而沒有經過任何處理的話,會執行它。
簡單的示例代碼如下:
var xssStr = '<script>console.log(1)</script>'; $('#test').html(xssStr);
控制台會打印出“1”。
同樣的情況也存在於jQuery.append(),因為jQuery.html()內部也是調用jQuery.append()。
既然會存在執行<script>腳本的情況,那么就會有xss風險。
解決辦法也很簡單,將需要作為參數的字符串進行轉義:
var xssEscapeStr = xssStr.replace(/</g, '<').replace(/>/g, '>');
這樣輸出在頁面上的只是單純的一段<script>字符串,並未執行。
但這並不是jQuery的一個bug,查看jQuery源碼,jQuery.append()對於<script>的處理似乎是有意為之。
jQuery文檔上是這樣解釋的:
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.
jQuery.append()等方法在設計的初衷就考慮到了允許執行其中的腳本,所以,jQuery不建議使用如URL、cookie、input輸入等內容作為append()的參數。
如果實在有需求,那就轉義吧。。。^_^