tarling
tarling

Reputation: 1957

How perform drag zoom with puppeteer for emulated devices

Has anyone managed to simulate a drag zoom interaction with puppeteer when the page is in emulated device mode. To do this as a user, you hold down the SHIFT key while dragging the mouse.

Unfortunately the following doesn't work

const cx = 160;
const cy = 284;
await page.mouse.move(cx, cy);
await page.keyboard.down('Shift');
await page.mouse.down();
await page.mouse.move(cx, cy - 300, {steps: 300});
await page.mouse.up();
await page.keyboard.up('Shift');

Upvotes: 1

Views: 763

Answers (2)

Edi Imanto
Edi Imanto

Reputation: 2509

I've found something similar with Input.dispatchMouseEvent answer by @Md Abu Taher. It is Input.synthetizePinchGesture which works perfectly when applied in my code.


async synthetizePinch (point: Point) {
    try {
        await this.client.send('Input.synthesizePinchGesture', {
            scaleFactor: 0.3,
            x: point.x,
            y: point.y,
            gestureSourceType: 'touch',
            relativeSpeed: 100,
        })
    } catch (error) {
        if (error instanceof Error) {
            console.log(error.message)
            this.errorLogger(error)
        }
    }
}

And you can call this function whenever you like:

const appSceneCanvas = await this.page.$(this.selector.appSceneCanvas)
const boundingBox = await appSceneCanvas.boundingBox()
await this.synthetizePinch({
    x: boundingBox.x + boundingBox.width / 2,
    y: boundingBox.y + boundingBox.height / 2,
})

Don't forget, it's still experimental. It may be buggy.

Upvotes: 0

Md. Abu Taher
Md. Abu Taher

Reputation: 18866

According to this conversation on this issue, they are not planning to add such feature. I'll quote their response,

I don't like adding puppeteer-level API for the WebPlatform's events. Puppeteer's clicks are way different to the WebPlatform's document.createEvent; having them as the only first-class API emphasizes that they're the recommended way to click things on the page.

I'd recommend to use a set of helper methods to cover your needs.

However you can do it this way,

await this._client.send('Input.dispatchMouseEvent', {
      type: 'mousePressed',
      button: this._button,
      x: this._x,
      y: this._y,
      modifiers: this._keyboard._modifiers,
      clickCount: (options.clickCount || 1)
});

Here is another code snippet to trigger one small mouse event (to be used with .evaluate function).

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent ('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}

Upvotes: 2

Related Questions