2013-07-16 54 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

刚刚尝试过它,它工作得很好,谢谢。 –