WebSocket Variable in ws-client.js

Hello, I have a question about using the WebSocket variable in ws-client.js

in the ‘init’ function of ws-client.js, we call new WebSocket(url)
I guess this is the same variable we defined in chattrbox/websockets-server.js
but we didn’t need to import this variable defined in another file (module?)

How does the code in our chattrbox/app/scripts/src/ws-client.js know about the WebSocket variable defined elsewhere?

Thanks, hope this makes sense.

Hi @davedauenhauer, the url variable you see referenced in ws-client comes from the init() function’s url parameter:

function init(url) {

Which is invoked from app.js:


So no worries, there is no magical relationship to the websocket-server.js server code :slight_smile: Does that help?

Thanks Jonathan, I stated my question poorly. I was asking about the variable ‘WebSocket’, not the ‘url’ parameter. so in our ws-client.js file, we call 'socket = new WebSocket(url);'
I’m guessing this is the same ‘WebSocket’ we defined in the websockets-server.js file in an earlier chapter… line 1 of this file is: var WebSocket = require(‘ws’);

I was wondering how the code in the file ws-client.js knew about this ‘WebSocket’. The code works OK, but I guess I was thinking we would have needed to write a statement at the top of ws-client.js such as: import WebSocket from ‘…/…/…/websockets-server.js’

Thanks much.

Ah, thanks for the clarification @davedauenhauer.

WebSocket is the browser’s built-in client Web API for connecting to a WebSocket server. It’s included on the global variable as window.WebSocket, so you can access it simply as WebSocket. It’s similar to how you can access the Promise and String constructor functions without require()ing anything, esp. since the browser doesn’t have a built-in require() function.

The browser’s WebSocket API is completely separate from the ws library you require() in your server-side code.

Thank you! Very helpful!