Skip to content

Commit

Permalink
feat(custom-element): support nonce option for injected style tags
Browse files Browse the repository at this point in the history
close #6530
  • Loading branch information
yyx990803 committed Aug 6, 2024
1 parent 60a88a2 commit bb4a02a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
17 changes: 17 additions & 0 deletions packages/runtime-dom/__tests__/customElement.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,23 @@ describe('defineCustomElement', () => {
await nextTick()
assertStyles(el, [`div { color: blue; }`, `div { color: red; }`])
})

test('with nonce', () => {
const Foo = defineCustomElement(
{
styles: [`div { color: red; }`],
render() {
return h('div', 'hello')
},
},
{ nonce: 'xxx' },
)
customElements.define('my-el-with-nonce', Foo)
container.innerHTML = `<my-el-with-nonce></my-el-with-nonce>`
const el = container.childNodes[0] as VueElement
const style = el.shadowRoot?.querySelector('style')!
expect(style.getAttribute('nonce')).toBe('xxx')
})
})

describe('async', () => {
Expand Down
3 changes: 3 additions & 0 deletions packages/runtime-dom/src/apiCustomElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ export type VueElementConstructor<P = {}> = {
export interface CustomElementOptions {
styles?: string[]
shadowRoot?: boolean
nonce?: string
}

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

0 comments on commit bb4a02a

Please sign in to comment.