Skip to content

Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.

fix(analytics): preserve data attributes in custom scripts

Timothy Yin7ac33de7ac40
diff --git a/app/utils/parseScriptTags.ts b/app/utils/parseScriptTags.ts
index 5e5cfb99..99301773 100644
--- a/app/utils/parseScriptTags.ts
+++ b/app/utils/parseScriptTags.ts
@@ -1,4 +1,6 @@
export interface ParsedScriptTag {
+ /** 第三方脚本的自定义配置属性 */
+ [key: `data-${string}`]: string | undefined
/** 外链脚本 URL */
src?: string
/** 内联脚本内容 */
@@ -68,6 +70,10 @@ function applyAttribute(
out: ParsedScriptTag,
): void {
const lower = name.toLowerCase()
+ if (lower.startsWith('data-') && lower.length > 5) {
+ out[lower as `data-${string}`] = value === true ? '' : value
+ return
+ }
if (!KNOWN_ATTRS.has(lower)) return
if (BOOLEAN_ATTRS.has(lower)) {
@@ -76,7 +82,11 @@ function applyAttribute(
}
if (lower === 'crossorigin') {
- if (value === true || value === 'anonymous' || value === 'use-credentials') {
+ if (
+ value === true ||
+ value === 'anonymous' ||
+ value === 'use-credentials'
+ ) {
out.crossorigin = value
}
return
@@ -93,9 +103,14 @@ function parseAttributes(attrs: string, out: ParsedScriptTag): void {
let match: RegExpExecArray | null
while ((match = ATTR_RE.exec(attrs)) !== null) {
const name = match[1]
- if (!name) continue // 类型守卫,同时避免无效匹配
+ if (!name) continue // 类型守卫,同时避免无效匹配
const value = match[2] ?? match[3] ?? match[4]
- const attrValue = value === undefined ? 'true' : value // 统一为 string
+ const attrValue =
+ value === undefined
+ ? name.toLowerCase().startsWith('data-')
+ ? ''
+ : 'true'
+ : value
applyAttribute(name, attrValue, out)
}
}
@@ -107,6 +122,7 @@ function parseAttributes(attrs: string, out: ParsedScriptTag): void {
* - 先剥离 HTML 注释
* - 同时匹配含内容与自闭合两种 <script> 形式
* - 解析 src/async/defer/type/crossorigin/integrity/nomodule/referrerpolicy/nonce
+ * - 保留 data-* 自定义属性,属性名转为小写,属性值保持字符串
* - 跳过既无 src 又无 innerHTML 的空脚本
* - 不过滤 type(application/ld+json、module 等原样保留)
* - 永不抛错,输入非法或为空时返回 []
diff --git a/tests/parse-script-tags.test.ts b/tests/parse-script-tags.test.ts
new file mode 100644
index 00000000..e78a0e92
--- /dev/null
+++ b/tests/parse-script-tags.test.ts
@@ -0,0 +1,82 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { createHead, renderSSRHead } from '@unhead/vue/server'
+import { parseScriptTags } from '../app/utils/parseScriptTags.ts'
+
+test('preserves the Umami website ID alongside standard script attributes', () => {
+ assert.deepEqual(
+ parseScriptTags(
+ '<script defer src="https://tongji.example.com/script.js" data-website-id="website-id"></script>',
+ ),
+ [
+ {
+ defer: true,
+ src: 'https://tongji.example.com/script.js',
+ 'data-website-id': 'website-id',
+ },
+ ],
+ )
+})
+
+test('normalizes data attribute names and preserves string and empty values', () => {
+ assert.deepEqual(
+ parseScriptTags(
+ `<script src="tracker.js" DATA-WEBSITE-ID='site' data-auto-track="false" data-count=0 data-empty="" data-enabled></script>`,
+ ),
+ [
+ {
+ src: 'tracker.js',
+ 'data-website-id': 'site',
+ 'data-auto-track': 'false',
+ 'data-count': '0',
+ 'data-empty': '',
+ 'data-enabled': '',
+ },
+ ],
+ )
+})
+
+test('keeps the standard attribute allowlist and inline script behavior', () => {
+ assert.deepEqual(
+ parseScriptTags(
+ '<script async defer nomodule type="module" nonce="token" onload="alert(1)" key="override" tagPosition="bodyClose" data-="invalid" unknown="value" data-config="inline">console.log("ok")</script>',
+ ),
+ [
+ {
+ async: true,
+ defer: true,
+ nomodule: true,
+ type: 'module',
+ nonce: 'token',
+ 'data-config': 'inline',
+ innerHTML: 'console.log("ok")',
+ },
+ ],
+ )
+ assert.deepEqual(
+ parseScriptTags('<script data-website-id="site"></script>'),
+ [],
+ )
+})
+
+test('renders data attributes in both head and body scripts through Unhead', async () => {
+ const head = createHead()
+ head.push({
+ script: ['head', 'bodyOpen'].flatMap((tagPosition) =>
+ parseScriptTags(
+ '<script defer src="tracker.js" data-website-id="site" data-auto-track="false" data-enabled></script>',
+ ).map((script) => ({
+ ...script,
+ tagPosition: tagPosition as 'head' | 'bodyOpen',
+ key: `cf-analytics-${tagPosition}-0`,
+ })),
+ ),
+ })
+ const rendered = await renderSSRHead(head)
+ for (const html of [rendered.headTags, rendered.bodyTagsOpen]) {
+ assert.match(html, /data-website-id="site"/)
+ assert.match(html, /data-auto-track="false"/)
+ assert.match(html, /data-enabled(?:="")?(?=[\s>])/)
+ assert.match(html, /src="tracker.js"/)
+ }
+})