0

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.

  • Inserting the code (copy & paste) of the clickElem function directly in the new tab works fine
  • CORS is not a problem since it's the same domain/subdomain/protocol
  • 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!

cyc8
  • 13
  • 5
  • Cors will be an issue if you use a different protocol such as https instead of http or a different subdomain such as www. Also the ports have to be the same. – John Dec 02 '21 at 12:59
  • In my case, it's the same domain, subdomain and protocol – cyc8 Dec 02 '21 at 14:08
  • Just use query selector on the window document then to see if you can access the dom. – John Dec 02 '21 at 14:09
  • This is working fine, I can access an element in the newly opened window through query selector – cyc8 Dec 02 '21 at 14:32

2 Answers2

0

Are you sure you are already inside your tab? I'm thinking about something you need to get the active tab like this one?

  • This looks like a comment rather than a direct answer to the question. You can consider adding this as a comment next time instead of posting it as an answer. – kennysliding Dec 06 '21 at 18:20
  • This looks like a comment rather than a direct answer to the question. You can consider adding this as a comment next time instead of posting it as an answer. – kennysliding Dec 06 '21 at 18:20
  • Thanks! Yes, I also believe a reference to the window is missing but I cannot figure out where. Trying to invoke an alert in the newly opened tab e.g. is functioning. Unfortunately, I cannot use the Chrome Extension API since it has to run as a bookmarklet and not as an extension. – cyc8 Dec 06 '21 at 21:21
0

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);
    
cyc8
  • 13
  • 5