I want to be able to mouse over a page, have it highlight the elements underneath the cursor (in the same way as the developer tools inspector), and when I click on the mouse obtain the XPath for the element. Enabling the element inspector and receiving the XPath to be done via code, and element selection by a human.
I can enable the devtools inspector behaviour by using Chrome Devtools Protocol and using the Overlay.setInspectMethod with inspectNode=searchForNode
.
Upon a mouse click I then receive a DOM.BackendNodeId of the clicked element from the Overlay.inspectNodeRequested
event
The devtools protocol does not seem to have any built in way to then obtain the XPath. So I found this javascript implementation of the Chrome Developer Tools Copy->Xpath functionality.
Whilst I can evaluate the javascript via CDT Protocol, after many hours of attempts, I cannot work out how to obtain a reference to the Node to execute the javascript function when all I have is the BackendNodeId.
Is there a way to get a reference in javascript to the node, or is there a way to get the nodes XPath in CDTProtocol ?
Found the proper solution
First I needed to obtain a reference to the Javascript object via
DOM.resolveNode, {backendNodeId: nId}
Then extract the objectId from the returned JSON object. Which will look something like
Then I can call whatever function I like, with the element as context
Runtime.callFunctionOn, {functionDeclaration: "function(){getXPathForElement(this)}", objectId: "{"injectedScriptId":3,"id":3}"