Skip to content
Snippets Groups Projects
websocket.html 2.22 KiB
Newer Older
  • Learn to ignore specific revisions
  • <script type="text/javascript">
        //Websocket connection
        $(document).ready(function(){
    
            if ('WebSocket' in window) {
                var ws = new WebSocket("{{=GET_URL(room_record)}}");
                ws.onopen = function () {
                    ws.initialConnect = true;
                };
                ws.onmessage = function(e) {
                    var firstColon = e.data.indexOf(":");
                    if(firstColon === -1) {
    
                        if(e.data.startsWith("+") || e.data.startsWith("-")) {
                            return;
                        }
    
                        set_error("{{=T('Invalid WebSocket data received')}}: '" + e.data + "'");
                        return;
                    }
    
                    var type = e.data.substring(0, firstColon);
                    var data = e.data.substring(firstColon + 1);
    
                    switch(type) {
                        case "roles":
    
                            roles = JSON.parse(atob(data));
    
    Nils G.'s avatar
    Nils G. committed
                            break;
                        case "role":
                            role_definition = JSON.parse(atob(data));
                            if(playerid in role_definition) {
                                role = role_definition[playerid]["role"];
    
    Nils G.'s avatar
    Nils G. committed
                                prompts = role_definition[playerid]["prompts"];
                                currentPrompt = 0;
    
    Nils G.'s avatar
    Nils G. committed
                            }
    
                            break;
                        default:
                            set_error("{{=T('Invalid WebSocket data received')}}: '" + type + "'");
                            return;
                    }
    
    Nils G.'s avatar
    Nils G. committed
                    render(role, roles);
    
    
                };
                ws.onerror = function(e) {
                    set_error("{{=T('Error')}}: "+e);
                };
                ws.onclose = function () {
                    if(ws.initialConnect) {
                        window.setTimeout(function() {
                            set_error("{{=T('WebSocket has closed')}}. {{=T('Please refresh this website')}}.");
                        }, 1000);
                    } else {
                        set_error("{{=T('WebSocket server is not responding')}}.");
                    }
                };
            } else {
                /* not supported */
                set_error("{{=T('WebSocket is not supported by your browser')}}.");
            }
    
        });
    </script>