javascriptdomchrome-devtools-protocol

Access particular DOM object with JavaScript using CDP


I am wondering if I can directly (like window.document.foo.bar) access to a particular node with JavaScript with the given DOM information.

I would start the question with the reason why I need this, but you can skip it.

  1. Why I need to do this.

I want to know all eventListeners associated with a DOM object outside of the main HTML using Chrome DevTools Protocol. This requires RemoteObjectId, and to get this I need to run Runtime.Evaluate over the target object.

  1. Example
<html>
  <head>
  </head>
  <body>
    <div>
      <p>...</p>
      <p>...</p>  <-- target object
      <p>...</p>
    </div>
    <div>
    </div>
  </body>
</html>

In the code above, I want to access the target object.

I can identify the location of the target object at main HTML side, by recursively checking parents and siblings starting from the target object.

The identified location is like; body.div(1st).p(2nd)

How can I do this with an evaluation? Runtime.Evaluate(window.document.body.div.p) accesses very first p, not the target p. But I cannot find a way to go the second one to get the remoteObjectId of the target p.


Solution

  • why don't you just use querySelector() and nth-child() for accessing the specific p?