如何以编程方式更新阴影 dom 内的输入?
How to programmatically update an input inside shadow dom?
Fiddle: https://jsfiddle.net/5zrwdjy7/2/
我正在尝试使用 Cypress 中的脚本自动执行击键,但目标网站使用 Web 组件作为输入。输入元素嵌套在 shadow dom 中。
我正在尝试按照以下常规输入触发输入事件:
const input = document.querySelector('input')
input.value = 'new value'
input.dispatchEvent(new Event('input'))
没有任何反应,值保持不变,输入中没有显示文本。是否可以以编程方式更新阴影内的输入 dom?
由于阴影封装了组件的细节,因此它阻止了 DOM 的常规遍历。要访问它:
- 查找灯下可用的 web 组件 DOM
- 遍历它的影子DOM:
const lightComponent = document.querySelector('web-component')
const shadowInput = lightComponent.shadowRoot.querySelector('input')
shadowInput.value = 'shadow value'
shadowInput.dispatchEvent(new Event('input'))
来源: https://javascript.info/shadow-dom-events
例子
// Create shadow dom inside <input-container>
customElements.define('input-container', class extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `<div><input type="text" /></div>`;
}
});
// Programmatically update input value inside shadow DOM
const lightComponent = document.querySelector('input-container')
const shadowInput = lightComponent.shadowRoot.querySelector('input')
shadowInput.value = 'Shadow value'
shadowInput.dispatchEvent(new Event('input'))
<body>
<label>Input inside shadow DOM</label>
<input-container></input-container>
</body>
Fiddle: https://jsfiddle.net/5zrwdjy7/2/
我正在尝试使用 Cypress 中的脚本自动执行击键,但目标网站使用 Web 组件作为输入。输入元素嵌套在 shadow dom 中。
我正在尝试按照以下常规输入触发输入事件:
const input = document.querySelector('input')
input.value = 'new value'
input.dispatchEvent(new Event('input'))
没有任何反应,值保持不变,输入中没有显示文本。是否可以以编程方式更新阴影内的输入 dom?
由于阴影封装了组件的细节,因此它阻止了 DOM 的常规遍历。要访问它:
- 查找灯下可用的 web 组件 DOM
- 遍历它的影子DOM:
const lightComponent = document.querySelector('web-component')
const shadowInput = lightComponent.shadowRoot.querySelector('input')
shadowInput.value = 'shadow value'
shadowInput.dispatchEvent(new Event('input'))
来源: https://javascript.info/shadow-dom-events
例子
// Create shadow dom inside <input-container>
customElements.define('input-container', class extends HTMLElement {
connectedCallback() {
const shadow = this.attachShadow({mode: 'open'});
shadow.innerHTML = `<div><input type="text" /></div>`;
}
});
// Programmatically update input value inside shadow DOM
const lightComponent = document.querySelector('input-container')
const shadowInput = lightComponent.shadowRoot.querySelector('input')
shadowInput.value = 'Shadow value'
shadowInput.dispatchEvent(new Event('input'))
<body>
<label>Input inside shadow DOM</label>
<input-container></input-container>
</body>