如何在新打开的window中使用XPath?

How to use XPath in a newly opened window?

使用下面的代码(用于小书签),我试图打开一个新的 window,查找某些跨度元素,然后单击它们中的每一个。但是,我无法通过 XPath 访问新 window 的代码。

JavaScript:

const w = window.open('https://example.com', 'Example', 'width=500, height=500');
w.clickElem = () => {
    const xpath = '//span[text()="Click here"]';
    const selectedNodeElements = w.document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null);
    let currentNode = selectedNodeElements.iterateNext();
    while (currentNode) {
        currentNode.click();
        currentNode = selectedNodeElements.iterateNext();
    }
}
setTimeout(w.clickElem, 8000);

当我尝试通过 currentNode.textContent 访问文本时,我收到以下错误:

"Error in protected function: Cannot read properties of null (reading 'textContent')"

感谢每一个提示!

你确定你已经在你的选项卡中了吗?我在想你需要什么来获得活动标签,比如 this one?

在反复检查我的代码并遇到 之后,我终于发现了自己的错误。 .iterateNext() 不起作用,因为上下文节点被错误地设置为 document。相反,它应该是 w.document 来引用新打开的 window.

const selectedNodeElements = w.document.evaluate(xpath, w.document, null, XPathResult.ANY_TYPE, null);