Skip to content

fix(customElement): allow defineCustomElement add style with nonce for content security policies (CSP) #8728

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
18 changes: 18 additions & 0 deletions packages/runtime-dom/__tests__/customElement.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,24 @@ describe('defineCustomElement', () => {
const style = el.shadowRoot?.querySelector('style')!
expect(style.textContent).toBe(`div { color: red; }`)
})

// #6530
test('style with nonce for content security policies (CSP)', () => {
const Foo = defineCustomElement({
nonce: 'noce-string-for-csp-policy',
styles: [`div { color: red; }`],
render() {
return h('div', 'hello')
}
})

customElements.define('my-styles-nonce', Foo)
container.innerHTML = `<my-styles-nonce></my-styles-nonce>`

const el = container.childNodes[0] as VueElement
const style = el.shadowRoot?.querySelector('style')!
expect(style.getAttribute('nonce')).toBe('noce-string-for-csp-policy')
})
})

describe('async', () => {
Expand Down
8 changes: 7 additions & 1 deletion packages/runtime-dom/src/apiCustomElement.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,10 @@ const BaseClass = (
typeof HTMLElement !== 'undefined' ? HTMLElement : class {}
) as typeof HTMLElement

type InnerComponentDef = ConcreteComponent & { styles?: string[] }
type InnerComponentDef = ConcreteComponent & {
styles?: string[]
nonce?: string
}

export class VueElement extends BaseClass {
/**
Expand Down Expand Up @@ -411,6 +414,9 @@ export class VueElement extends BaseClass {
styles.forEach(css => {
const s = document.createElement('style')
s.textContent = css
// nonce string for content security policy
// https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/nonce
this._def.nonce && s.setAttribute('nonce', this._def.nonce)
this.shadowRoot!.appendChild(s)
// record for HMR
if (__DEV__) {
Expand Down