Fixes view script loading and request handling on the web frontend

Executes the view scripts after the application scripts have loaded, both on
the initial page load and during AJAX navigation, instead of running them
during HTML parsing when the API helpers are not defined yet. Sends an empty
JSON object for requests without a payload, because FastEndpoints parses the
JSON body when the content type is application/json. Adds the antiforgery
token to the management views that issue protected write requests.
This commit is contained in:
BinaryAlley committed 2026-08-26 19:16:21 +03:00
1 parent ccefb65c83
commit ba9a49b0db
14 files changed
+109 -70

No files matched your search

@@ -18,6 +18,8 @@
@inject IViewLocalizer _localizer
@inject IUrlService _urlService
@Html.AntiForgeryToken()
<form id="authorization-permissions-form" method="post" class="w-100 h-100 mx-auto pl-10 pr-10 pt-10 pb-10">
<div id="authorization-permissions-container">
<input type="hidden" name="authorization-users-selected-id" id="authorization-users-selected-id" value="" />
@@ -101,7 +103,8 @@
</form>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
@@ -16,6 +16,8 @@
@inject IViewLocalizer _localizer
@inject IUrlService _urlService
@Html.AntiForgeryToken()
<form id="authorization-roles-form" method="post" class="w-100 h-100 mx-auto pl-10 pr-10 pt-10 pb-10">
<div id="authorization-roles-container">
<input type="hidden" name="authorization-roles-selected-id" id="authorization-roles-selected-id" value="" />
@@ -81,7 +83,8 @@
</form>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
@@ -148,7 +148,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
@@ -145,7 +145,8 @@
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
let isInitialized = false;
@@ -69,7 +69,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
@@ -63,7 +63,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
@@ -57,7 +57,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
@@ -98,7 +98,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
@@ -24,7 +24,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
let isInitialized = false;
@@ -15,6 +15,8 @@
@inject IUrlService _urlService
@inject IViewLocalizer _localizer
@Html.AntiForgeryToken()
<style>
/* main container */
.td-scan {
@@ -158,7 +160,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
let isInitialized = false;
@@ -237,7 +237,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
@@ -46,7 +46,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
let isInitialized = false;
@@ -86,7 +86,8 @@
</div>
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
<!-- The "text/plain" type is a design choice, not a mistake: it keeps the browser from executing this view script during HTML parsing, before site.js defines the API helpers it calls (callApiGetAsync, callApiPostAsync, ...). site.js (which loads deferred) executes these scripts once it is loaded, both on the initial page load and during AJAX navigation. -->
<script type="text/plain" data-form="@scriptId">
// create cleanup registry for this view
const cleanupFunctions = [];
let isInitialized = false;
+77 -57
View File
@@ -76,11 +76,12 @@ async function callApiPostAsync(url, data, options = {}) {
if (token)
headers['RequestVerificationToken'] = token;
}
// make the request
// make the request; when no data is provided, send an empty JSON object, because FastEndpoints parses the JSON body when
// the content type is application/json, so an empty body would fail to deserialize
const response = await fetch(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(data)
body: JSON.stringify(data ?? {})
});
if (response.redirected) // if a redirect is requested, perform it
window.location.href = response.url;
@@ -131,11 +132,12 @@ async function callApiPutAsync(url, data, options = {}) {
if (token)
headers['RequestVerificationToken'] = token;
}
// make the request
// make the request; when no data is provided, send an empty JSON object, because FastEndpoints parses the JSON body when
// the content type is application/json, so an empty body would fail to deserialize
const response = await fetch(url, {
method: 'PUT',
headers: headers,
body: JSON.stringify(data)
body: JSON.stringify(data ?? {})
});
if (response.redirected) // if a redirect is requested, perform it
window.location.href = response.url;
@@ -233,6 +235,10 @@ function initializeNavigation() {
// handle browser back/forward
window.addEventListener('popstate', handlePopStateAsync);
// execute the view scripts of the initially loaded page, now that the application scripts are loaded; the view scripts are
// stored with a non-executable type, so the browser does not run them before the application scripts are available
processViewScriptsAsync(document.querySelector('[data-section="scripts"]'));
}
/**
@@ -277,6 +283,72 @@ async function handlePopStateAsync(e) {
}
}
/**
* Executes the view scripts of a page, creating executable script elements from the scripts found in the provided source container.
* The view scripts are stored with a non-executable type, so that the browser does not run them before the application scripts
* are loaded; they are executed here, once the application scripts are available.
* @param {Element|null} sourceContainer - The element containing the view scripts to execute.
* @returns {Promise<void>} A promise that completes when the external view scripts have loaded.
*/
async function processViewScriptsAsync(sourceContainer) {
const viewScripts = Array.from(sourceContainer?.getElementsByTagName('script') ?? []);
if (viewScripts.length === 0)
return;
// get or create scripts container
let scriptsContainer = document.querySelector('[data-section="scripts"]');
if (!scriptsContainer) {
scriptsContainer = document.createElement('div');
scriptsContainer.setAttribute('data-section', 'scripts');
document.body.appendChild(scriptsContainer);
}
// clear existing scripts in container
scriptsContainer.innerHTML = '';
// process view scripts
for (const script of viewScripts) {
const scriptId = script.getAttribute('data-form');
// remove existing script with same Id if it exists
const existingScript = document.querySelector(`script[data-form="${scriptId}"]`);
if (existingScript)
existingScript.remove();
const newScript = document.createElement('script');
// copy script attributes, except the type, which is overridden so that the stored non-executable scripts are executed
Array.from(script.attributes).forEach(attr => {
if (attr.name !== 'type')
newScript.setAttribute(attr.name, attr.value);
});
// handle both inline and external scripts
if (script.src) {
newScript.src = script.src;
// wait for external script to load
await new Promise((resolve, reject) => {
newScript.onload = resolve;
newScript.onerror = reject;
});
} else {
// wrap inline scripts in a safety check
newScript.textContent = `
(async function() {
const safeGetElement = (id) => document.getElementById(id);
const safeAddEventListener = (element, e, handler) => {
if (element)
element.addEventListener(e, handler);
};
${script.textContent}
// call Initialize function, if defined in this script's scope
if (typeof InitializeAsync === 'function')
await InitializeAsync();
})();
`;
}
// add script to scripts container
scriptsContainer.appendChild(newScript);
}
}
/**
* Loads new page content and updates the URL and history if required.
* @param {string} url - URL to fetch new content from.
@@ -340,59 +412,7 @@ async function updateContentAsync(url, addToHistory) {
document.body.appendChild(newScript);
}
// process view scripts
const viewScripts = doc.querySelector('[data-section="scripts"]')?.getElementsByTagName('script') || [];
// get or create scripts container
let scriptsContainer = document.querySelector('[data-section="scripts"]');
if (!scriptsContainer) {
scriptsContainer = document.createElement('div');
scriptsContainer.setAttribute('data-section', 'scripts');
document.body.appendChild(scriptsContainer);
}
// clear existing scripts in container
scriptsContainer.innerHTML = '';
// process view scripts
for (const script of viewScripts) {
const scriptId = script.getAttribute('data-form');
// remove existing script with same Id if it exists
const existingScript = document.querySelector(`script[data-form="${scriptId}"]`);
if (existingScript)
existingScript.remove();
const newScript = document.createElement('script');
// copy script attributes
Array.from(script.attributes).forEach(attr => {
newScript.setAttribute(attr.name, attr.value);
});
// handle both inline and external scripts
if (script.src) {
newScript.src = script.src;
// wait for external script to load
await new Promise((resolve, reject) => {
newScript.onload = resolve;
newScript.onerror = reject;
});
} else {
// wrap inline scripts in a safety check
newScript.textContent = `
(async function() {
const safeGetElement = (id) => document.getElementById(id);
const safeAddEventListener = (element, e, handler) => {
if (element)
element.addEventListener(e, handler);
};
${script.textContent}
// call Initialize function, if defined in this script's scope
if (typeof InitializeAsync === 'function')
await InitializeAsync();
})();
`;
}
// add script to scripts container
scriptsContainer.appendChild(newScript);
}
await processViewScriptsAsync(doc.querySelector('[data-section="scripts"]'));
// bind navigation links in the new content
bindNavigationLinks();