Skip to content
This repository has been archived by the owner on Jan 19, 2022. It is now read-only.

Executing random code on a DOM node

captainbrosset edited this page Oct 29, 2014 · 1 revision

If for whatever reason the upstream protocol doesn't provide the necessary command in the DOM domain to retrieve some information about a DOM node, it is possible to execute JS code on the DOM node to retrieve this information anyway. Here's how you do it:

A Node object returned by the protocol, can be resolved to a RemoteObject, which is the representation for any runtime javascript object.

So, first, resolve the node to a runtime object:

// Get the runtime object for this dom node
let {object} = yield this.rpc.request("DOM.resolveNode", {
  nodeId: node.handle.nodeId
});

Then, using this runtime object, you can execute any javascript code you want on it. All you have to do is provide a function declaration string where this is the DOM node itself. In the code below, we'll be retrieving the bounding client rect:

// Execute the function on the resolved runtime object
let functionDecl = "function() { return this.getBoundingClientRect(); }";

let {result} = yield this.rpc.request("Runtime.callFunctionOn", {
  objectId: object.objectId,
  functionDeclaration: functionDecl,
  arguments: []
});

After the response is received, result will be a RemoteObject. So in order to access the properties of the actual runtime js object mirrored by this RemoteObject, a last step is needed:

// Get all the properties from the returned object
let response = yield this.rpc.request("Runtime.getProperties", {
  objectId: result.objectId
});
Clone this wiki locally