Skip to content

Commit

Permalink
fix(html): escape html attribute (#18067)
Browse files Browse the repository at this point in the history
Co-authored-by: 翠 / green <green@sapphi.red>
  • Loading branch information
sunnylost and sapphi-red authored Sep 10, 2024
1 parent d81dc59 commit 5983f36
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
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',
},
]
},
},
},
],
})

0 comments on commit 5983f36

Please sign in to comment.