Created
March 25, 2021 12:34
-
-
Save gabrielbusarello/181bf0ff6424c410a7137371f8a04af3 to your computer and use it in GitHub Desktop.
Drag and Drop for Puppeteer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async dragAndDrop(page, originSelector, destinationSelector) { | |
const origin = await page.waitForSelector(originSelector); | |
const destination = await page.waitForSelector(destinationSelector); | |
const originBox = await origin.boundingBox(); | |
const destinationBox = await destination.boundingBox(); | |
const lastPositionCoordenate = (box) => ({ | |
x: box.x + box.width / 2, | |
y: box.y + box.height / 2, | |
}); | |
const getPayload = (box) => ({ | |
bubbles: true, | |
cancelable: true, | |
screenX: lastPositionCoordenate(box).x, | |
screenY: lastPositionCoordenate(box).y, | |
clientX: lastPositionCoordenate(box).x, | |
clientY: lastPositionCoordenate(box).y, | |
}); | |
const pageFunction = async (_originSelector, _destinationSelector, originPayload, destinationPayload) => { | |
const _origin = document.querySelector(_originSelector); | |
let _destination = document.querySelector(_destinationSelector); | |
_destination = _destination.lastElementChild || _destination; | |
_origin.dispatchEvent(new MouseEvent('pointerdown', originPayload)); | |
_origin.dispatchEvent(new DragEvent('dragstart', originPayload)); | |
await new Promise((resolve) => setTimeout(resolve, 2000)); | |
_destination.dispatchEvent(new MouseEvent('dragenter', destinationPayload)); | |
_destination.dispatchEvent(new MouseEvent('pointerup', destinationPayload)); | |
_destination.dispatchEvent(new MouseEvent('drop', destinationPayload)); | |
_origin.dispatchEvent(new DragEvent('dragend', destinationPayload)); | |
}; | |
await page.evaluate( | |
pageFunction, | |
originSelector, | |
destinationSelector, | |
getPayload(originBox), | |
getPayload(destinationBox), | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment