how to connect to websocket in Lightning?

Tested WebSockets in Open CTI adapter url. It works perfectly fine. Change the ws:// uri as per your setup in below source code.

<html>
<head>
   <script type="text/javascript" src="http://na11.salesforce.com/support/api/28.0/interaction.js"></script>
   <script type="text/javascript">
       var callback = function (response) {
           if (response.result) {
              alert('Screen pop was set successfully.');
           }
           else {
              alert('Screen pop failed.' + result.error);
           }
        };
       function screenPop() {
                //Invokes API method
                sforce.interaction.screenPop('/001x0000003DGQR', true, callback);
        }
</script>


        <script type="text/javascript">
            var webSocket;
            var data = "";

            function openSocket()
            {
                // Open server socket
                if (webSocket !== undefined && webSocket.readyState !== WebSocket.CLOSED) {
                    alert("WebSocket is already opened");
                    return;
                }

                webSocket = new WebSocket("ws://xxx.xxx.xxx.xxx:8080/sample/sampleendpoint");

                if (webSocket === undefined)
                {
                    alert("Error creating socket...");
                    return;
                }

                webSocket.onopen = function()
                {
                    alert("in onopen callback");
                }

                webSocket.onmessage = function(event)
                {
                    alert("in onmessage callback   " + data);
                }

                webSocket.onclose = function()
                {
                    alert("in onclose callback");
                }
            }

        </script>

</head>
<body>
       <button onclick="openSocket();">Open Socket</button>
</body>
</html>

This is a known limitation with lightning currently

However I see that your script is trying to make the call to a third party URL .You will need to identify the script and try and make the callout via apex .From lightning due to security limitations no XHR will be allowed .

The other workaround will be to proxy this via the Visualforce .There is a neat article on how to do this

Blog article from developer force

Also if the webserver is just returning a JSON without any processing you may download the file and keep inside static resource .


I'm not sure when this went live as there's still an open idea on this topic, but WebSockets are now supported in CSP Trusted Site settings.

Add you wss:// endpoint via Setup -> CSP Trusted Site and you should be good to go.