Skip to content

Commit

Permalink
fix(dev-server-core): use script origin to connect websocket
Browse files Browse the repository at this point in the history
  • Loading branch information
LarsDenBakker committed Apr 29, 2021
1 parent a2e8914 commit e7efd5b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
8 changes: 8 additions & 0 deletions .changeset/unlucky-buttons-chew.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@web/dev-server-core': patch
'@web/dev-server': patch
'@web/test-runner': patch
'@web/test-runner-core': patch
---

use script origin to connect websocket
10 changes: 4 additions & 6 deletions packages/dev-server-core/src/web-sockets/webSocketsPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,9 @@ export const webSocketScript = `<!-- injected by web-dev-server -->
<script type="module" src="${NAME_WEB_SOCKET_IMPORT}"></script>`;

export function webSocketsPlugin(): Plugin {
let origin: string;
return {
name: 'web-sockets',

serverStart({ config }) {
origin = `ws${config.http2 ? 's' : ''}://${config.hostname ?? 'localhost'}:${config.port}`;
},

resolveImport({ source }) {
if (source === NAME_WEB_SOCKET_IMPORT) {
return NAME_WEB_SOCKET_IMPORT;
Expand All @@ -24,6 +19,9 @@ export function webSocketsPlugin(): Plugin {
if (context.path === NAME_WEB_SOCKET_IMPORT) {
// this code is inlined because TS compiles to CJS but we need this to be ESM
return `
const { protocol, host } = new URL(import.meta.url);
const webSocketUrl = \`ws\${protocol === 'https:' ? 's' : ''}://\${host}/${NAME_WEB_SOCKET_API}\`;
export let webSocket;
export let webSocketOpened;
export let sendMessage;
Expand All @@ -45,7 +43,7 @@ function setupWebSocket() {
} else {
webSocket =
'WebSocket' in window
? new WebSocket('${origin}/${NAME_WEB_SOCKET_API}')
? new WebSocket(webSocketUrl)
: null;
webSocketOpened = new Promise(resolve => {
if (!webSocket) {
Expand Down

0 comments on commit e7efd5b

Please sign in to comment.