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', () => {
.returns([{ src: 'http://test-host:3001/script.js' }]);
});
it('falls back to using origin info from the last <script> tag in the document', () => {
const url = processUrlTemplate(
'{current_scheme}://{current_host}:2000/style.css',
fakeDocument
);
assert.equal(url, 'http://test-host:2000/style.css');
it('throws if script origin cannot be determined', () => {
assert.throws(() => {
const template = '{current_scheme}://{current_host}:2000/style.css';
processUrlTemplate(template, fakeDocument);
}, 'Could not process URL template because script origin is unknown');
});
it('does not try to determine the origin if there are no URL template params', () => {
......
......@@ -14,19 +14,12 @@ function extractOrigin(url) {
}
function currentScriptOrigin(document_ = document) {
try {
let scriptEl = /** @type {HTMLScriptElement} */ (document_.currentScript);
if (!scriptEl) {
// Fallback for IE 11.
const scripts = document_.querySelectorAll('script');
scriptEl = scripts[scripts.length - 1];
}
return extractOrigin(scriptEl.src);
} catch (err) {
const scriptEl = /** @type {HTMLScriptElement|null} */ (document_.currentScript);
if (!scriptEl) {
// Function was called outside of initial script execution.
return null;
}
return extractOrigin(scriptEl.src);
}
/**
......@@ -52,6 +45,10 @@ export default function processUrlTemplate(url, document_ = document) {
if (origin) {
url = url.replace('{current_host}', origin.hostname);
url = url.replace('{current_scheme}', origin.protocol);
} else {
throw new Error(
'Could not process URL template because script origin is unknown'
);
}
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