Skip to content

Instantly share code, notes, and snippets.

@rikschennink
Created May 23, 2024 08:18
Show Gist options
  • Save rikschennink/ac68b75d4606d035898d87b2bffc41b2 to your computer and use it in GitHub Desktop.
Save rikschennink/ac68b75d4606d035898d87b2bffc41b2 to your computer and use it in GitHub Desktop.
A quick script to simulate dragging an element with PointerEvent
// drag simulation function
async function runDragSimulation(path, options) {
const { wait = 1000, shouldRelease = true } = options;
// helper to wait for x milliseconds
const sleep = (time) =>
new Promise((resolve) => {
setTimeout(() => {
resolve();
}, time);
});
// helper to dispatch pointer events
const dispatchPointerEvent = (point, type) => {
document.elementFromPoint(point.x, point.y).dispatchEvent(
new PointerEvent(type, {
clientX: point.x,
clientY: point.y,
bubbles: true,
})
);
};
// we remember last point so we can fire pointerup when we're done
let lastPoint;
for (const [index, point] of path.entries()) {
await sleep(wait);
const type = index === 0 ? "pointerdown" : "pointermove";
dispatchPointerEvent(point, type);
lastPoint = point;
}
// exit if should not drop
if (!shouldRelease) return;
// wait at end
await sleep(wait);
// fire pointerup on last event
dispatchPointerEvent(lastPoint, "pointerup");
}
// how to use
runDragSimulation(
[
// grab
{
x: 50,
y: 50,
},
// move
{
x: 100,
y: 100,
},
// move
{
x: 200,
y: 100,
},
// move & up
{
x: 200,
y: 200,
},
],
{
// wait time between operations
wait: 1000,
// should fire pointerup?
shouldRelease: true,
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment