Websocket icon indicating copy to clipboard operation
Websocket copied to clipboard

Vue and websocket

Open YnievesDotNet opened this issue 8 years ago • 3 comments

I try to use the demo code, on one app and I use vue in this app, but the code is broken and I recive this error

Uncaught TypeError: Cannot read property 'addEventListener' of null

Thanks.

Yoinier.

YnievesDotNet avatar Jun 12 '17 14:06 YnievesDotNet

Maybe a little bit of code would help a lot :-).

Hywan avatar Jun 12 '17 14:06 Hywan

That is my code

...
        <input type="text" id="input" placeholder="Message…" />
        <hr />
        <pre id="output"></pre>
...
<script>
    var host   = 'ws://127.0.0.1:8000';
    var socket = null;
    var input  = document.getElementById('input');
    var output = document.getElementById('output');
    var print  = function (message) {
        var samp       = document.createElement('samp');
        samp.innerHTML = message + '\n';
        output.appendChild(samp);

        return;
    };

    input.addEventListener('keyup', function (evt) {
        if (13 === evt.keyCode) {
            var msg = input.value;

            if (!msg) {
                return;
            }

            try {
                socket.send(msg);
                input.value = '';
                input.focus();
            } catch (e) {
                console.log(e);
            }

            return;
        }
    });

    try {
        socket = new WebSocket(host);
        socket.onopen = function () {
            print('connection is opened');
            input.focus();

            return;
        };
        socket.onmessage = function (msg) {
            print(msg.data);

            return;
        };
        socket.onclose = function () {
            print('connection is closed');

            return;
        };
    } catch (e) {
        console.log(e);
    }
</script>
<script src="/js/app.js"></script>

Thanks, Yoinier.

YnievesDotNet avatar Jun 12 '17 14:06 YnievesDotNet

Hello @YnievesDotNet This error means the DomElement input is not yet ready when the Javascript is executed. You should embed the javascript code on function and execute it after the onload event.

Pierozi avatar Jun 12 '17 15:06 Pierozi