2012-03-28 21 views
13

我的HTML 5應用程序的用戶可以在表單中輸入他的名字,並且此名稱將顯示在別處。更具體地說,它將成爲某個HTML元素的innerHTMLDojo工具包:如何​​轉義HTML字符串?

問題是,如果您在表單中輸入有效的HTML標記(即某種HTML注入),則可以利用此問題。

用戶名只存儲和顯示在客戶端,所以最終用戶本人是唯一受影響的人,但它仍然是馬虎。

在我把它放入Dojo中的元素innerHTML之前,有沒有辦法讓字符串轉義?我猜Dojo在某一點上確實有這樣的功能(dojo.string.escape()),但它在版本1.7中不存在。

謝謝。

回答

16
dojox.html.entities.encode(myString); 
+0

工程就像一個魅力,我不必重新發明輪子。謝謝! – 2012-03-28 11:17:41

0

檢查的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, "&lt;"). 
     replace(/>/g, "&gt;"). 
     replace(/"/g, "&quot;"); 
    }); 
    } 
    // 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

0

我試圖找出其他圖書館如何實現這個功能,我偷了以下從MooTools的的想法:

var property = (document.createElement('div').textContent == null) ? 'innerText': 'textContent'; 
elem[property] = "<" + "script" + ">" + "alert('a');" + "</" + "script" + ">"; 

所以根據MooTools,可以是innerText或textContent屬性,它可以轉義HTML。

5

Dojo的模塊dojox/html/entities用於HTML轉義。不幸的是,the official documentation仍然只提供1.7之前的非AMD示例。

下面是一個例子如何使用與AMD該模塊:

var str = "<strong>some text</strong>" 
require(['dojox/html/entities'], function(entities) { 
var escaped = entities.encode(str) 
console.log(escaped) 
}) 

輸出:

&lt;strong&gt;some text&lt;/strong&gt;

0

作爲道場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 
    ); 
});