With the code below (intended for a bookmarklet), 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.
clickElem function directly in the new tab works fineJavaScript:
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!
I finally found my own mistake after going through my code on and on and coming across this answer. The .iterateNext() didn't work because the context node was wrongly set to document. Instead, it should be w.document to reference the newly opened window.
const selectedNodeElements = w.document.evaluate(xpath, w.document, null, XPathResult.ANY_TYPE, null);