# Dynamically Enable/Disable WebSocket node

**URL:** <https://discourse.nodered.org/t/dynamically-enable-disable-websocket-node/55638>\
**Category:** Core Development\
**Created:** [24 December 2021 01:13 UTC](https://discourse.nodered.org/t/dynamically-enable-disable-websocket-node/55638 "2021-12-24T01:13:23Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![UnborN](https://avatars.discourse-cdn.com/v4/letter/u/4491bb/32.png) [@UnborN](https://discourse.nodered.org/u/UnborN)\
**Post date:** [25 December 2021 17:21 UTC](https://discourse.nodered.org/t/dynamically-enable-disable-websocket-node/55638/2 "2021-12-25T17:21:05Z")

</div>

Hello .. i think the core Websocket nodes connect and stay connected and i didnt see a way to force a disconnect.

You could load the `ws` library using the `functionExternalModules` option in a Function node as a workaround in order to have better control.

I dont know much about websockets but here's a flow to demostrate it using an online open test server.  
(in this example when a msg with the expected data is received .. we force a disconnect )

```auto
[{"id":"6ff8ddd581cb52e0","type":"function","z":"54efb553244c241f","name":"","func":"const ws = new WebSocket('wss://demo.piesocket.com/v3/channel_1?api_key=oCdCMcMPQpbvNjUIzqtvF1d2X2okWpDQj4AwARJuAgtjhzKxVEjQU6IdCjwm&notify_self');\nnode.status({ fill: \"green\", shape: \"dot\", text: \"Connected\" });\n// ws.onopen = function () {\n// console.log('WebSocket Client Connected');\n// ws.send('Hi this is web client.');\n// };\nws.onmessage = function (e) {\n node.warn({ payload: e.data });\n\n if (e.data.startsWith(\"cpu\")) {\n node.warn(\"Msg received. Closing Websocket\");\n node.status({ fill: \"red\", shape: \"dot\", text: \"Disconnected\" });\n ws.close();\n }\n\n};\n\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[{"var":"WebSocket","module":"ws"}],"x":470,"y":1120,"wires":[["a0a621998adc2697"]]},{"id":"98c5874423d2fd40","type":"inject","z":"54efb553244c241f","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":300,"y":1120,"wires":[["6ff8ddd581cb52e0"]]},{"id":"a0a621998adc2697","type":"debug","z":"54efb553244c241f","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":650,"y":1120,"wires":[]}]

```

ps. you can read how to setup [functionExternalModules](https://nodered.org/docs/user-guide/writing-functions#using-the-functionexternalmodules-option) here

![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/a/2/a2e079030bc2a6c4624ca728bb3ff9ceec1f2129.png)

---

_[View the full topic](https://discourse.nodered.org/t/dynamically-enable-disable-websocket-node/55638)._
