Skip to content

Commit 2bce1ea

Browse files
authored
Show messages for users if the ROOT_URL is wrong, show JavaScript errors (#18971)
* ROOT_URL issues: some users did wrong to there app.ini config, then: * The assets can not be loaded (AppSubUrl != "" and users try to access http://host:3000/) *The ROOT_URL is wrong, then many URLs in Gitea are broken. Now Gitea show enough information to users. * JavaScript error issues, there are many users affected by JavaScript errors, some are caused by frontend bugs, some are caused by broken customized templates. If these JS errors can be found at first time, then maintainers do not need to ask about how bug occurs again and again. * Some people like to modify the `head.tmpl`, so we separate the script part to `head_script.tmpl`, then it's much safer. * use specialized CSS class "js-global-error", end users still have a chance to hide error messages by customized CSS styles.
1 parent ea8622d commit 2bce1ea

File tree

7 files changed

+118
-52
lines changed

7 files changed

+118
-52
lines changed

templates/base/footer.tmpl

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
<script src='https://hcaptcha.com/1/api.js' async></script>
2323
{{end}}
2424
{{end}}
25-
<script src="{{AssetUrlPrefix}}/js/index.js?v={{MD5 AppVer}}"></script>
25+
<script src="{{AssetUrlPrefix}}/js/index.js?v={{MD5 AppVer}}" onerror="alert('Failed to load asset files from ' + this.src + ', please make sure the asset files can be accessed and the ROOT_URL setting in app.ini is correct.')"></script>
2626
{{template "custom/footer" .}}
2727
</body>
2828
</html>

templates/base/head.tmpl

+3-42
Original file line numberDiff line numberDiff line change
@@ -19,51 +19,12 @@
1919
<link rel="alternate" type="application/atom+xml" title="" href="{{.FeedURL}}.atom">
2020
<link rel="alternate" type="application/rss+xml" title="" href="{{.FeedURL}}.rss">
2121
{{end}}
22-
<script>
23-
<!-- /* eslint-disable */ -->
24-
window.config = {
25-
appVer: '{{AppVer}}',
26-
appSubUrl: '{{AppSubUrl}}',
27-
assetUrlPrefix: '{{AssetUrlPrefix}}',
28-
runModeIsProd: {{.RunModeIsProd}},
29-
customEmojis: {{CustomEmojis}},
30-
useServiceWorker: {{UseServiceWorker}},
31-
csrfToken: '{{.CsrfToken}}',
32-
pageData: {{.PageData}},
33-
requireTribute: {{.RequireTribute}},
34-
notificationSettings: {{NotificationSettings}}, {{/*a map provided by NewFuncMap in helper.go*/}}
35-
enableTimeTracking: {{EnableTimetracking}},
36-
{{if .RequireTribute}}
37-
tributeValues: Array.from(new Map([
38-
{{ range .Participants }}
39-
['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}',
40-
name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink}}'}],
41-
{{ end }}
42-
{{ range .Assignees }}
43-
['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}',
44-
name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink}}'}],
45-
{{ end }}
46-
{{ range .MentionableTeams }}
47-
['{{$.MentionableTeamsOrg}}/{{.Name}}', {key: '{{$.MentionableTeamsOrg}}/{{.Name}}', value: '{{$.MentionableTeamsOrg}}/{{.Name}}',
48-
name: '{{$.MentionableTeamsOrg}}/{{.Name}}', avatar: '{{$.MentionableTeamsOrgAvatar}}'}],
49-
{{ end }}
50-
]).values()),
51-
{{end}}
52-
mermaidMaxSourceCharacters: {{MermaidMaxSourceCharacters}},
53-
{{/* this global i18n object should only contain general texts. for specialized texts, it should be provided inside the related modules by: (1) API response (2) HTML data-attribute (3) PageData */}}
54-
i18n: {
55-
copy_success: '{{.i18n.Tr "copy_success"}}',
56-
copy_error: '{{.i18n.Tr "copy_error"}}',
57-
error_occurred: '{{.i18n.Tr "error.occurred"}}',
58-
network_error: '{{.i18n.Tr "error.network_error"}}',
59-
},
60-
};
61-
{{/* in case some pages don't render the pageData, we make sure it is an object to prevent null access */}}
62-
window.config.pageData = window.config.pageData || {};
63-
</script>
6422
<link rel="icon" href="{{AssetUrlPrefix}}/img/logo.svg" type="image/svg+xml">
6523
<link rel="alternate icon" href="{{AssetUrlPrefix}}/img/favicon.png" type="image/png">
6624
<link rel="stylesheet" href="{{AssetUrlPrefix}}/css/index.css?v={{MD5 AppVer}}">
25+
26+
{{template "base/head_script" .}}
27+
6728
<noscript>
6829
<style>
6930
.dropdown:hover > .menu { display: block; }

templates/base/head_script.tmpl

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
{{/*
2+
==== DO NOT EDIT ====
3+
If you are customizing Gitea, please do not change this file.
4+
If you introduce mistakes in it, Gitea JavaScript code wouldn't run correctly.
5+
*/}}
6+
<script>
7+
<!-- /* eslint-disable */ -->
8+
window.addEventListener('error', function(e) {window._globalHandlerErrors=window._globalHandlerErrors||[]; window._globalHandlerErrors.push(e);});
9+
window.config = {
10+
appVer: '{{AppVer}}',
11+
appUrl: '{{AppUrl}}',
12+
appSubUrl: '{{AppSubUrl}}',
13+
assetUrlPrefix: '{{AssetUrlPrefix}}',
14+
runModeIsProd: {{.RunModeIsProd}},
15+
customEmojis: {{CustomEmojis}},
16+
useServiceWorker: {{UseServiceWorker}},
17+
csrfToken: '{{.CsrfToken}}',
18+
pageData: {{.PageData}},
19+
requireTribute: {{.RequireTribute}},
20+
notificationSettings: {{NotificationSettings}}, {{/*a map provided by NewFuncMap in helper.go*/}}
21+
enableTimeTracking: {{EnableTimetracking}},
22+
{{if .RequireTribute}}
23+
tributeValues: Array.from(new Map([
24+
{{ range .Participants }}
25+
['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}',
26+
name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink}}'}],
27+
{{ end }}
28+
{{ range .Assignees }}
29+
['{{.Name}}', {key: '{{.Name}} {{.FullName}}', value: '{{.Name}}',
30+
name: '{{.Name}}', fullname: '{{.FullName}}', avatar: '{{.AvatarLink}}'}],
31+
{{ end }}
32+
{{ range .MentionableTeams }}
33+
['{{$.MentionableTeamsOrg}}/{{.Name}}', {key: '{{$.MentionableTeamsOrg}}/{{.Name}}', value: '{{$.MentionableTeamsOrg}}/{{.Name}}',
34+
name: '{{$.MentionableTeamsOrg}}/{{.Name}}', avatar: '{{$.MentionableTeamsOrgAvatar}}'}],
35+
{{ end }}
36+
]).values()),
37+
{{end}}
38+
mermaidMaxSourceCharacters: {{MermaidMaxSourceCharacters}},
39+
{{/* this global i18n object should only contain general texts. for specialized texts, it should be provided inside the related modules by: (1) API response (2) HTML data-attribute (3) PageData */}}
40+
i18n: {
41+
copy_success: '{{.i18n.Tr "copy_success"}}',
42+
copy_error: '{{.i18n.Tr "copy_error"}}',
43+
error_occurred: '{{.i18n.Tr "error.occurred"}}',
44+
network_error: '{{.i18n.Tr "error.network_error"}}',
45+
},
46+
};
47+
{{/* in case some pages don't render the pageData, we make sure it is an object to prevent null access */}}
48+
window.config.pageData = window.config.pageData || {};
49+
</script>

web_src/js/bootstrap.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import {joinPaths} from './utils.js';
2+
3+
// DO NOT IMPORT window.config HERE!
4+
// to make sure the error handler always works, we should never import `window.config`, because some user's custom template breaks it.
5+
6+
// This sets up the URL prefix used in webpack's chunk loading.
7+
// This file must be imported before any lazy-loading is being attempted.
8+
__webpack_public_path__ = joinPaths(window?.config?.assetUrlPrefix ?? '/', '/');
9+
10+
export function showGlobalErrorMessage(msg) {
11+
const pageContent = document.querySelector('.page-content');
12+
if (!pageContent) return;
13+
const el = document.createElement('div');
14+
el.innerHTML = `<div class="ui container negative message center aligned js-global-error" style="white-space: pre-line;"></div>`;
15+
el.childNodes[0].textContent = msg;
16+
pageContent.prepend(el.childNodes[0]);
17+
}
18+
19+
/**
20+
* @param {ErrorEvent} e
21+
*/
22+
function processWindowErrorEvent(e) {
23+
showGlobalErrorMessage(`JavaScript error: ${e.message} (${e.filename} @ ${e.lineno}:${e.colno}). Open browser console to see more details.`);
24+
}
25+
26+
function initGlobalErrorHandler() {
27+
if (!window.config) {
28+
showGlobalErrorMessage(`Gitea JavaScript code couldn't run correctly, please check your custom templates`);
29+
}
30+
31+
// we added an event handler for window error at the very beginning of <script> of page head
32+
// the handler calls `_globalHandlerErrors.push` (array method) to record all errors occur before this init
33+
// then in this init, we can collect all error events and show them
34+
for (const e of window._globalHandlerErrors || []) {
35+
processWindowErrorEvent(e);
36+
}
37+
// then, change _globalHandlerErrors to an object with push method, to process further error events directly
38+
window._globalHandlerErrors = {'push': (e) => processWindowErrorEvent(e)};
39+
}
40+
41+
initGlobalErrorHandler();

web_src/js/features/common-global.js

+19-1
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@ import 'jquery.are-you-sure';
33
import {mqBinarySearch} from '../utils.js';
44
import createDropzone from './dropzone.js';
55
import {initCompColorPicker} from './comp/ColorPicker.js';
6+
import {showGlobalErrorMessage} from '../bootstrap.js';
67

7-
const {csrfToken} = window.config;
8+
const {appUrl, csrfToken} = window.config;
89

910
export function initGlobalFormDirtyLeaveConfirm() {
1011
// Warn users that try to leave a page after entering data into a form.
@@ -343,3 +344,20 @@ export function initGlobalButtons() {
343344
});
344345
});
345346
}
347+
348+
/**
349+
* Too many users set their ROOT_URL to wrong value, and it causes a lot of problems:
350+
* * Cross-origin API request without correct cookie
351+
* * Incorrect href in <a>
352+
* * ...
353+
* So we check whether current URL starts with AppUrl(ROOT_URL).
354+
* If they don't match, show a warning to users.
355+
*/
356+
export function checkAppUrl() {
357+
const curUrl = window.location.href;
358+
if (curUrl.startsWith(appUrl)) {
359+
return;
360+
}
361+
showGlobalErrorMessage(`Your ROOT_URL in app.ini is ${appUrl} but you are visiting ${curUrl}
362+
You should set ROOT_URL correctly, otherwise the web may not work correctly.`);
363+
}

web_src/js/index.js

+5-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import './publicpath.js';
1+
// bootstrap module must be the first one to be imported, it handles webpack lazy-loading and global errors
2+
import './bootstrap.js';
23

34
import $ from 'jquery';
45
import {initVueEnv} from './components/VueComponentLoader.js';
@@ -39,6 +40,7 @@ import {
3940
} from './features/repo-issue.js';
4041
import {initRepoEllipsisButton, initRepoCommitLastCommitLoader} from './features/repo-commit.js';
4142
import {
43+
checkAppUrl,
4244
initFootLanguageMenu,
4345
initGlobalButtonClickOnEnter,
4446
initGlobalButtons,
@@ -82,7 +84,6 @@ $.fn.tab.settings.silent = true;
8284
$.fn.checkbox.settings.enableEnterKey = false;
8385

8486
initVueEnv();
85-
8687
$(document).ready(() => {
8788
initGlobalCommon();
8889

@@ -169,4 +170,6 @@ $(document).ready(() => {
169170
initUserAuthWebAuthn();
170171
initUserAuthWebAuthnRegister();
171172
initUserSettings();
173+
174+
checkAppUrl();
172175
});

web_src/js/publicpath.js

-6
This file was deleted.

0 commit comments

Comments
 (0)