Binding This example keyboard Enter key (the Enter) , sending the trigger message action WebSocket
<Script type = "text / JavaScript"> // monitor keyboard Enter key pressed actions document.onkeydown = function (E) { IF ((E || Event) == 13 is .keyCode ) SENDMSG (); } ; // ///////////// & Create message reception monitoring processing operation ///////////////////////// WS / / after ws created protocol connection, it has to create and establish a connection to the server var ws = new new the WebSocket ( "ws:? //127.0.0.1/chat CURRENT_USER username = {{}}" ); // ///// ////////////// WebSocket received message ////////////////////////// ws.onmessage = function ( recv) { // $ ( "# contents") append ( "<p>" + recv.data + "</ p>");. // jquery add content to the div var div = document.getElementById ( 'Contents' ); div. the innerHTML = div.innerHTML recv.data + + '<br>' ; div.scrollTop = div.scrollHeight; // current remains lowermost roller div }; // //////////// ////// WebSocket message transmission //////////////////////// function SENDMSG () { $ ( '#MSG'). Val ($ ( '#MSG') Val () TRIM ());.. // remove the spaces before and after the input var MSG = $ ( "MSG #" ) .val (); IF (MSG && msg.length>0) { data = { // username:username, msg:msg }; ws.send(JSON.stringify(data)); $("#msg").val(""); }else { console.log('内容不许为空') } } </script>