]> git.ipfire.org Git - thirdparty/vuejs/core.git/commitdiff
feat(custom-element): support nonce option for injected style tags
authorEvan You <evan@vuejs.org>
Tue, 6 Aug 2024 07:41:43 +0000 (15:41 +0800)
committerEvan You <evan@vuejs.org>
Tue, 6 Aug 2024 07:41:54 +0000 (15:41 +0800)
close #6530

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

index 9378d721930713f3cc0c44b5d3442aef530783f0..70af88ed466e4a73d97ae39b552ac62f64bd269c 100644 (file)
@@ -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', () => {
index 964f43441e8e4073cb3f7fdc2c1b79bb3a8e0fbc..6aa40c8330e54fa775e213026747d54614e67bd6 100644 (file)
@@ -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
@@ -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