Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(html): escape html attribute #18067

Merged
merged 2 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import MagicString from 'magic-string'
import colors from 'picocolors'
import type { DefaultTreeAdapterMap, ParserError, Token } from 'parse5'
import { stripLiteral } from 'strip-literal'
import escapeHtml from 'escape-html'
import type { Plugin } from '../plugin'
import type { ViteDevServer } from '../server'
import {
Expand Down Expand Up @@ -1510,7 +1511,7 @@ function serializeAttrs(attrs: HtmlTagDescriptor['attrs']): string {
if (typeof attrs[key] === 'boolean') {
res += attrs[key] ? ` ${key}` : ``
} else {
res += ` ${key}=${JSON.stringify(attrs[key])}`
res += ` ${key}="${escapeHtml(attrs[key])}"`
}
}
return res
Expand Down
5 changes: 5 additions & 0 deletions playground/html/__tests__/html.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,3 +471,8 @@ test('html fallback works non browser accept header', async () => {
).status,
).toBe(200)
})

test('escape html attribute', async () => {
const el = await page.$('.unescape-div')
expect(el).toBeNull()
})
17 changes: 17 additions & 0 deletions playground/html/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -214,5 +214,22 @@ ${
]
},
},
{
name: 'escape-html-attribute',
transformIndexHtml: {
order: 'post',
handler() {
return [
{
tag: 'link',
attrs: {
href: `"><div class=unescape-div>extra content</div>`,
},
injectTo: 'body',
},
]
},
},
},
],
})
Loading