Skip to content

Commit 153448d

Browse files
perry-mitchellSpaceK33z
authored andcommitted
Improve detection to get current client script
* Use 'document.scripts' instead of document.getElementsByTagName * Use document.currentScript with document.scripts as fallback
1 parent 4cdb14c commit 153448d

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

client/index.js

+18-3
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,30 @@
11
var url = require('url');
22
var SockJS = require("sockjs-client");
33
var stripAnsi = require('strip-ansi');
4+
5+
function getCurrentScriptSource() {
6+
// try to get the current script
7+
if (document.currentScript) {
8+
return document.currentScript.getAttribute("src");
9+
}
10+
// fall back to getting all scripts in the document
11+
var scriptElements = document.scripts || [],
12+
currentScript = scriptElements[scriptElements.length - 1];
13+
if (currentScript) {
14+
return currentScript.getAttribute("src");
15+
}
16+
// fail as there was no script to use
17+
throw new Error("Failed to get current script source");
18+
}
19+
420
var urlParts;
521
if (typeof __resourceQuery === "string" && __resourceQuery) {
622
// If this bundle is inlined, use the resource query to get the correct url.
723
urlParts = url.parse(__resourceQuery.substr(1));
824
} else {
925
// Else, get the url from the <script> this file was called with.
10-
var scriptElements = document.getElementsByTagName("script");
11-
var scriptHost = scriptElements[scriptElements.length-1].getAttribute("src");
12-
scriptHost = scriptHost && scriptHost.replace(/\/[^\/]+$/, "");
26+
var scriptHost = getCurrentScriptSource();
27+
scriptHost = scriptHost.replace(/\/[^\/]+$/, "");
1328
urlParts = url.parse((scriptHost ? scriptHost : "/"), false, true);
1429
}
1530

0 commit comments

Comments
 (0)