2013-07-16 57 views
0

這是輸出我得到的檢索,當我運行代碼時,HTML標籤:問題與火力

[19:01:06] User: <a href="http://www.google.com" target="_blank" >http://www.google.com </a> 

它不創造它只顯示一個href標記的鏈接。

這是什麼使鏈接:

function linkify(inputText) { 
var replacedText, replacePattern1, replacePattern2, replacePattern3; 

//URLs starting with http://, https://, or ftp:// 
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim; 
replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>'); 

//URLs starting with "www." (without // before it, or it'd re-link the ones done above). 
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim; 
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>'); 

return replacedText; 

}

所以在本教程中聊天框我發送文本火力點列表,例如:

text=linkify(text); 
    myDataRef.push({timestamp: timestamp, name: name, text: text, emote: emote}); 

這是什麼顯示部分看起來像:

function displayChatMessage(timestamp, name, text, emote) { 

     $('<div/>').text('['+timestamp+'] ').append($('<name/>').text(name+': ')).append($('<em/>').text(text)).appendTo($('#messagesDiv')); 
} 
$('#messagesDiv')[0].scrollTop = $('#messagesDiv')[0].scrollHeight; 

};

我試圖插入其他html標籤,但不會工作。 整個代碼只是基於教程聊天並從那裏開始工作。

回答

0

jQuery的.text()轉義HTML,以便它顯示爲文本而不是呈現爲HTML。聊天示例有意使用這個,以避免HTML Script Injection

$('<div/>').text('['+timestamp+'] ').append($('<name/>').text(name+': ')).append($('<em/>').html(text)).appendTo($('#messagesDiv')); 

注意使用的.html(文本),而不是的.text(文本):通過改變渲染代碼,你可以「修復」您的代碼。 但這不是安全的。現在,任何使用聊天的人都可以用<script src="http://mysite.com/my-malicious-javascript.js"></script>作爲聊天消息輸入消息,其他人都會運行該javascript。

也許這jQuery插件可能是一個更好的解決方案:。https://github.com/uudashr/jquery-linkify(即不接收方的linkification在想必安全的方式(雖然我沒有看過的代碼)

+0

謝謝你,我會給Jquery首先嚐試一下,不要讓它變得不那麼安全,那麼它必須是。 –

+0

剛剛嘗試過它,它工作得很好,謝謝。 –