From 95d1b4a4a296e8cf949eaec0519d4008985fa7a8 Mon Sep 17 00:00:00 2001 From: "Sven R. Kunze" Date: Mon, 22 Feb 2021 17:18:26 +0100 Subject: [PATCH] complete websocket URL - use the current host and port - use ws for http and wss for https - these changes allow sending cookies of the current site --- src/htmx.js | 9 +++++++-- www/attributes/hx-ws.md | 3 ++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/htmx.js b/src/htmx.js index 5c7c3c7d..b996c5f4 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -1052,8 +1052,13 @@ return (function () { } function processWebSocketSource(elt, wssSource) { - if (wssSource.indexOf("ws:") !== 0 && wssSource.indexOf("wss:") !== 0) { - wssSource = "wss:" + wssSource; + if (wssSource.indexOf("/") == 0) { // complete absolute paths only + var base_part = location.hostname + (location.port ? ':'+location.port: ''); + if (location.protocol == 'https:') { + wssSource = "wss://" + base_part + wssSource; + } else if (location.protocol == 'http:') { + wssSource = "ws://" + base_part + wssSource; + } } var socket = htmx.createWebSocket(wssSource); socket.onerror = function (e) { diff --git a/www/attributes/hx-ws.md b/www/attributes/hx-ws.md index 88258331..aa89c8d3 100644 --- a/www/attributes/hx-ws.md +++ b/www/attributes/hx-ws.md @@ -8,7 +8,8 @@ title: htmx - hx-ws The `hx-ws` allows you to work with [Web Sockets](https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications) directly from HTML. The value of the attribute can be one or more of the following, separated by commas: -* `connect:` or `connect::` - A URL to establish an `WebSocket` connection against. Prefixes `ws` or `wss` can optionally be specified. If not specified, HTMX defaults to add the `wss` prefix to the url. +* `connect:` or `connect::` - A URL to establish an `WebSocket` connection against. +* Prefixes `ws` or `wss` can optionally be specified. If not specified, HTMX defaults to add the location's scheme-type, host and port to have browsers send cookies via websockets. * `send` - Sends a message to the nearest websocket based on the trigger value for the element (either the natural event of the event specified by [`hx-trigger`])