英文:
Can not access text inside Shadow DOM using playwright
问题
我正在尝试使用 Playwright 来断言如下的文本,该文本位于没有与特定文本相关联的标签的 open shadow root 中。这些文本位于表格单元格内。
<div>
<table-cell>
#shadow-root (open)
"Text content"
</table-cell>
我试图断言 #shadow-root 中的 "Text content",它位于 shadow DOM 下面。我能够唯一地定位 <table-cell>
,但无法获取其中的文本。无论我尝试使用哪种方法来检索文本,它总是返回一个空字符串或对象。以下是我尝试的 TypeScript 代码示例:
const text = this.page.locator('table-cell').innerText();
我能够获取其他位于具有与文本相关的标签的 shadow root 内的文本。但在这种情况下,这个特定的文本行没有与其相关联的任何标签,因此这些方法无法像其他情况那样工作。
如何获取仅包含文本而不包含任何标签的 #shadow-root 内容?
英文:
I am trying to use playwright to assert text like below which is inside open shadow root which has no tags associated to that specific text. These texts are inside table cells.
<div>
<table-cell>
#shadow-root (open)
"Text content"
</table-cell>
I am trying to assert "Text content" which is under shadow DOM. I was able to uniquely locate <table-cell> but can not get the text inside it. It always return an empty string or object depends on the method I tried to retrieve the text. Example typescript code I tried is below,
const text = this.page.locator('table-cell').innerText();
I was able to get other texts which are inside shadow root which has a tag associated with that text. But in this case this specific text line don't have any tag associated to that so the methods aren't working as for other scenarios.
How do I get the contents of #shadow-root if it only contains the text, without any tags ?
答案1
得分: 1
"innerText" 是在 "HTMLElement" 上的一个属性
一个 shadowRoot 不是一个 "HTMLElement",并且没有 "innerText" 属性。
它确实有一个 "innerHTML" 属性:https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot
let text = document.querySelector("your-element").shadowRoot.innerHTML
获取到的文本
英文:
innerText
is a property on HTMLElement
A shadowRoot is not a HTMLElement
and does not have an innerText
property.
It does have a innerHTML
property: https://developer.mozilla.org/en-US/docs/Web/API/ShadowRoot
let text = document.querySelector("your-element").shadowRoot.innerHTML
Gets you the text
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论