Commit 0b12d7f9 authored by Robert Knight's avatar Robert Knight

Make `processUrlTemplate` fail if script origin is unknown

`document.currentScript` is supported by all browsers that we support.
If it returns `null` this indicates that it was called in the wrong
context and so fail loudly to make this obvious.
parent 834f96ac
...@@ -38,12 +38,11 @@ describe('processUrlTemplate', () => { ...@@ -38,12 +38,11 @@ describe('processUrlTemplate', () => {
.returns([{ src: 'http://test-host:3001/script.js' }]); .returns([{ src: 'http://test-host:3001/script.js' }]);
}); });
it('falls back to using origin info from the last <script> tag in the document', () => { it('throws if script origin cannot be determined', () => {
const url = processUrlTemplate( assert.throws(() => {
'{current_scheme}://{current_host}:2000/style.css', const template = '{current_scheme}://{current_host}:2000/style.css';
fakeDocument processUrlTemplate(template, fakeDocument);
); }, 'Could not process URL template because script origin is unknown');
assert.equal(url, 'http://test-host:2000/style.css');
}); });
it('does not try to determine the origin if there are no URL template params', () => { it('does not try to determine the origin if there are no URL template params', () => {
......
...@@ -14,19 +14,12 @@ function extractOrigin(url) { ...@@ -14,19 +14,12 @@ function extractOrigin(url) {
} }
function currentScriptOrigin(document_ = document) { function currentScriptOrigin(document_ = document) {
try { const scriptEl = /** @type {HTMLScriptElement|null} */ (document_.currentScript);
let scriptEl = /** @type {HTMLScriptElement} */ (document_.currentScript);
if (!scriptEl) { if (!scriptEl) {
// Fallback for IE 11. // Function was called outside of initial script execution.
const scripts = document_.querySelectorAll('script');
scriptEl = scripts[scripts.length - 1];
}
return extractOrigin(scriptEl.src);
} catch (err) {
return null; return null;
} }
return extractOrigin(scriptEl.src);
} }
/** /**
...@@ -52,6 +45,10 @@ export default function processUrlTemplate(url, document_ = document) { ...@@ -52,6 +45,10 @@ export default function processUrlTemplate(url, document_ = document) {
if (origin) { if (origin) {
url = url.replace('{current_host}', origin.hostname); url = url.replace('{current_host}', origin.hostname);
url = url.replace('{current_scheme}', origin.protocol); url = url.replace('{current_scheme}', origin.protocol);
} else {
throw new Error(
'Could not process URL template because script origin is unknown'
);
} }
return url; return url;
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment