How to use XPath in a newly opened window?

With the code below, I am trying to open a new window, look for certain span-elements, and click each of them. However, I cannot access the code of the new window through XPath.

  • Inserting the code (copy & paste) of the clickElem function directly in the new tab works fine
  • CORS shouldn’t be a problem since it’s the same domain
  • I’ve been also following this answer.

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);

When I try to access the text via currentNode.textContent I receive following error:

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

Grateful for every hint!