From 4bd855c66b2f8922b3cb18a380cd938c72a1b632 Mon Sep 17 00:00:00 2001 From: JoelEinbinder Date: Thu, 13 Jul 2017 18:32:34 -0700 Subject: [PATCH] Use getBoundingClientRect instead of DOM.BoxModel (#76) This patch re-implements `page.click()` and `page.focus()` using `page.evaluate` --- lib/Page.js | 70 +++++++++++++++++++++++++++++------------------------ 1 file changed, 39 insertions(+), 31 deletions(-) diff --git a/lib/Page.js b/lib/Page.js index 43566eac5af..9939cd296c3 100644 --- a/lib/Page.js +++ b/lib/Page.js @@ -509,31 +509,36 @@ class Page extends EventEmitter { * @param {!Promise} */ async click(selector) { - try { - const nodeId = await this._querySelector(selector); - let boxModel = (await this._client.send('DOM.getBoxModel', { nodeId })).model.content; - let x = Math.round((boxModel[0] + boxModel[4]) / (2 * this._screenDPI)); - let y = Math.round((boxModel[1] + boxModel[5]) / (2 * this._screenDPI)); - - this._client.send('Input.dispatchMouseEvent', { - type: 'mouseMoved', - x, y - }); - this._client.send('Input.dispatchMouseEvent', { - type: 'mousePressed', - button: 'left', - x, y, - clickCount: 1 - }); - await this._client.send('Input.dispatchMouseEvent', { - type: 'mouseReleased', - button: 'left', - x, y, - clickCount: 1 - }); - } finally { - await this._client.send('DOM.disable'); - } + let center = await this.evaluate(selector => { + let node = document.querySelector(selector); + if (!node) + return null; + let rect = node.getBoundingClientRect(); + return { + x: (rect.left + rect.right) / 2, + y: (rect.top + rect.bottom) / 2 + }; + }, selector); + if (!center) + throw new Error('No node found for selector: ' + selector); + let x = Math.round(center.x / this._screenDPI); + let y = Math.round(center.y / this._screenDPI); + this._client.send('Input.dispatchMouseEvent', { + type: 'mouseMoved', + x, y + }); + this._client.send('Input.dispatchMouseEvent', { + type: 'mousePressed', + button: 'left', + x, y, + clickCount: 1 + }); + await this._client.send('Input.dispatchMouseEvent', { + type: 'mouseReleased', + button: 'left', + x, y, + clickCount: 1 + }); } /** @@ -541,12 +546,15 @@ class Page extends EventEmitter { * @param {!Promise} */ async focus(selector) { - try { - const nodeId = await this._querySelector(selector); - await this._client.send('DOM.focus', { nodeId }); - } finally { - await this._client.send('DOM.disable'); - } + let success = await this.evaluate(selector => { + let node = document.querySelector(selector); + if (!node) + return false; + node.focus(); + return true; + }, selector); + if (!success) + throw new Error('No node found for selector: ' + selector); } /**