Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: make current script detection more robust on edge cases #630

Merged
merged 4 commits into from Apr 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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