Skip to content

Commit

Permalink
fix: make current script detection more robust on edge cases (#630)
Browse files Browse the repository at this point in the history
  • Loading branch information
pmmmwh committed Apr 25, 2022
1 parent d5d2716 commit d859c9f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
6 changes: 3 additions & 3 deletions docs/API.md
Expand Up @@ -226,7 +226,7 @@ You can reference implementations inside the [`sockets`](https://github.com/pmmm

#### `sockHost`

Default: `window.location.hostname`
Default: Parsed from current URL

Type: `string`

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

#### `sockPort`

Default: `window.location.port`
Default: Parsed from current URL

Type: `number`

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

#### `sockPath`

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

Type: `string`

Expand Down
23 changes: 15 additions & 8 deletions sockets/utils/getCurrentScriptSource.js
Expand Up @@ -5,16 +5,23 @@
function getCurrentScriptSource() {
// `document.currentScript` is the most accurate way to get the current running script,
// but is not supported in all browsers (most notably, IE).
if (document.currentScript) {
if ('currentScript' in document) {
// In some cases, `document.currentScript` would be `null` even if the browser supports it:
// e.g. asynchronous chunks on Firefox.
// We should not fallback to the list-approach as it would not be safe.
if (document.currentScript == null) return;
return document.currentScript.getAttribute('src');
}

// Fallback to getting all scripts running in the document.
const scriptElements = document.scripts || [];
const scriptElementsWithSrc = Array.prototype.filter.call(scriptElements, function (elem) {
return elem.getAttribute('src');
});
if (scriptElementsWithSrc.length) {
// Fallback to getting all scripts running in the document,
// and finding the last one injected.
else {
const scriptElementsWithSrc = Array.prototype.filter.call(
document.scripts || [],
function (elem) {
return elem.getAttribute('src');
}
);
if (!scriptElementsWithSrc.length) return;
const currentScript = scriptElementsWithSrc[scriptElementsWithSrc.length - 1];
return currentScript.getAttribute('src');
}
Expand Down

0 comments on commit d859c9f

Please sign in to comment.