[英]Dojo Toolkit: how to escape an HTML string?
我的HTML 5應用程序的用戶可以在表單中輸入他的名字,此名稱將顯示在其他地方。 更具體地說,它將成為某些HTML元素的innerHTML
。
問題是,如果您在表單中輸入有效的HTML標記,即可以使用某種HTML注入,則可以利用此功能。
用戶名只存儲並顯示在客戶端,因此最終用戶自己是唯一受影響的人,但它仍然很草率。
有沒有辦法在將它放入Dojo中的元素innerHTML
之前轉義字符串? 我猜Dojo在某一點上實際上確實有這樣一個函數( dojo.string.escape()
)但它在版本1.7中不存在。
謝謝。
dojox.html.entities.encode(myString);
Dojo具有用於HTML轉義的模塊dojox/html/entities
。 不幸的是, 官方文檔仍然只提供1.7之前的非AMD示例。
以下是如何將該模塊與AMD一起使用的示例:
var str = "<strong>some text</strong>"
require(['dojox/html/entities'], function(entities) {
var escaped = entities.encode(str)
console.log(escaped)
})
輸出:
<strong>some text</strong>
從Dojo 1.10開始,轉義函數仍然是字符串模塊的一部分。
http://dojotoolkit.org/api/?qs=1.10/dojo/string
以下是如何將其用作簡單的模板系統。
require([
'dojo/string'
], function(
string
){
var template = '<h1>${title}</h1>';
var message = {title: 'Hello World!<script>alert("Doing something naughty here...")</script>'}
var html = string.substitute(
template
, message
, string.escape
);
});
檢查dojo.replace
這個例子:
require(["dojo/_base/lang"], function(lang){
function safeReplace(tmpl, dict){
// convert dict to a function, if needed
var fn = lang.isFunction(dict) ? dict : function(_, name){
return lang.getObject(name, false, dict);
};
// perform the substitution
return lang.replace(tmpl, function(_, name){
if(name.charAt(0) == '!'){
// no escaping
return fn(_, name.slice(1));
}
// escape
return fn(_, name).
replace(/&/g, "&").
replace(/</g, "<").
replace(/>/g, ">").
replace(/"/g, """);
});
}
// that is how we use it:
var output = safeReplace("<div>{0}</div",
["<script>alert('Let\' break stuff!');</script>"]
);
});
資料來源: http : //dojotoolkit.org/reference-guide/1.7/dojo/replace.html#escaping-substitutions
我試圖找出其他庫如何實現這個功能,我從MooTools中偷走了以下內容:
var property = (document.createElement('div').textContent == null) ? 'innerText': 'textContent';
elem[property] = "<" + "script" + ">" + "alert('a');" + "</" + "script" + ">";
因此,根據MooTools,可以使用innerText或textContent屬性來轉義HTML。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.