Skip to content

Commit d859c9f

Browse files
authored
fix: make current script detection more robust on edge cases (#630)
1 parent d5d2716 commit d859c9f

File tree

2 files changed

+18
-11
lines changed

2 files changed

+18
-11
lines changed

docs/API.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ You can reference implementations inside the [`sockets`](https://github.com/pmmm
226226

227227
#### `sockHost`
228228

229-
Default: `window.location.hostname`
229+
Default: Parsed from current URL
230230

231231
Type: `string`
232232

@@ -237,7 +237,7 @@ Useful if you set `devServer.sockHost` to something other than `window.location.
237237

238238
#### `sockPort`
239239

240-
Default: `window.location.port`
240+
Default: Parsed from current URL
241241

242242
Type: `number`
243243

@@ -248,7 +248,7 @@ Useful if you set `devServer.sockPort` to something other than `window.location.
248248

249249
#### `sockPath`
250250

251-
Default: `/sockjs-node`
251+
Default: `/ws` for WDS v4, `/sockjs-node` for WDS v3
252252

253253
Type: `string`
254254

sockets/utils/getCurrentScriptSource.js

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,23 @@
55
function getCurrentScriptSource() {
66
// `document.currentScript` is the most accurate way to get the current running script,
77
// but is not supported in all browsers (most notably, IE).
8-
if (document.currentScript) {
8+
if ('currentScript' in document) {
9+
// In some cases, `document.currentScript` would be `null` even if the browser supports it:
10+
// e.g. asynchronous chunks on Firefox.
11+
// We should not fallback to the list-approach as it would not be safe.
12+
if (document.currentScript == null) return;
913
return document.currentScript.getAttribute('src');
1014
}
11-
12-
// Fallback to getting all scripts running in the document.
13-
const scriptElements = document.scripts || [];
14-
const scriptElementsWithSrc = Array.prototype.filter.call(scriptElements, function (elem) {
15-
return elem.getAttribute('src');
16-
});
17-
if (scriptElementsWithSrc.length) {
15+
// Fallback to getting all scripts running in the document,
16+
// and finding the last one injected.
17+
else {
18+
const scriptElementsWithSrc = Array.prototype.filter.call(
19+
document.scripts || [],
20+
function (elem) {
21+
return elem.getAttribute('src');
22+
}
23+
);
24+
if (!scriptElementsWithSrc.length) return;
1825
const currentScript = scriptElementsWithSrc[scriptElementsWithSrc.length - 1];
1926
return currentScript.getAttribute('src');
2027
}

0 commit comments

Comments
 (0)