Simulating pinch-to-zoom with Puppeteer on mobile device emulation

Hey everyone! I’m trying to figure out how to mimic the pinch-to-zoom gesture using Puppeteer when emulating a mobile device. You know, the thing where you use two fingers to zoom in on a touchscreen?

I’ve tried a few things, but no luck so far. Here’s what I attempted:

const startX = 200;
const startY = 300;
const endY = 100;

await page.touchscreen.tap(startX, startY);
await page.touchscreen.touchMove(startX, endY);
await page.touchscreen.touchEnd();

This doesn’t seem to work though. Has anyone cracked this? I’d really appreciate any tips or tricks you might have! Thanks in advance for your help!

I’ve actually tackled this issue before in one of my projects. The key is to simulate two touch points moving simultaneously. Here’s a snippet that worked for me:

await page.evaluate(() => {
  const touch1 = new Touch({identifier: 1, target: document.body, clientX: 100, clientY: 100});
  const touch2 = new Touch({identifier: 2, target: document.body, clientX: 200, clientY: 200});
  
  const touchStart = new TouchEvent('touchstart', {touches: [touch1, touch2]});
  document.body.dispatchEvent(touchStart);
  
  // Simulate pinch
  const touch1End = new Touch({identifier: 1, target: document.body, clientX: 150, clientY: 150});
  const touch2End = new Touch({identifier: 2, target: document.body, clientX: 250, clientY: 250});
  
  const touchMove = new TouchEvent('touchmove', {touches: [touch1End, touch2End]});
  document.body.dispatchEvent(touchMove);
  
  const touchEnd = new TouchEvent('touchend', {touches: []});
  document.body.dispatchEvent(touchEnd);
});

This approach directly manipulates touch events, which more accurately simulates pinch-to-zoom. Remember to adjust the coordinates based on your specific use case.

hey flyingleaf, i had similar issue. try using page.touchscreen.touchMove() with multiple touch points. something like:

await Promise.all([
page.touchscreen.touchMove(100, 100, {touchPointID: 1}),
page.touchscreen.touchMove(200, 200, {touchPointID: 2})
]);

this simulates two fingers moving. hope it helps!