Skip to content

Commit bb4a02a

Browse files
committed
feat(custom-element): support nonce option for injected style tags
close #6530
1 parent 60a88a2 commit bb4a02a

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

packages/runtime-dom/__tests__/customElement.spec.ts

+17
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,23 @@ describe('defineCustomElement', () => {
718718
await nextTick()
719719
assertStyles(el, [`div { color: blue; }`, `div { color: red; }`])
720720
})
721+
722+
test('with nonce', () => {
723+
const Foo = defineCustomElement(
724+
{
725+
styles: [`div { color: red; }`],
726+
render() {
727+
return h('div', 'hello')
728+
},
729+
},
730+
{ nonce: 'xxx' },
731+
)
732+
customElements.define('my-el-with-nonce', Foo)
733+
container.innerHTML = `<my-el-with-nonce></my-el-with-nonce>`
734+
const el = container.childNodes[0] as VueElement
735+
const style = el.shadowRoot?.querySelector('style')!
736+
expect(style.getAttribute('nonce')).toBe('xxx')
737+
})
721738
})
722739

723740
describe('async', () => {

packages/runtime-dom/src/apiCustomElement.ts

+3
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ export type VueElementConstructor<P = {}> = {
4848
export interface CustomElementOptions {
4949
styles?: string[]
5050
shadowRoot?: boolean
51+
nonce?: string
5152
}
5253

5354
// defineCustomElement provides the same type inference as defineComponent
@@ -513,8 +514,10 @@ export class VueElement
513514
}
514515
this._styleChildren.add(owner)
515516
}
517+
const nonce = this._def.nonce
516518
for (let i = styles.length - 1; i >= 0; i--) {
517519
const s = document.createElement('style')
520+
if (nonce) s.setAttribute('nonce', nonce)
518521
s.textContent = styles[i]
519522
this.shadowRoot!.prepend(s)
520523
// record for HMR

0 commit comments

Comments
 (0)