Simulate Drag and Drop of Files with Playwright
If you’re trying to simulate drag and drop of files in Playwright for testing, you’ll need to use page.dispatchEvent
to accomplish this.
There is a short note on how to do this in the docs:
1 2 3 |
// Note you can only create DataTransfer in Chromium and Firefox const dataTransfer = await page.evaluateHandle(() => new DataTransfer()); await page.dispatchEvent('#source', 'dragstart', { dataTransfer }); |
But this is hardly enough to get it working!
It seems like I’m not the only one.
Good news is that it’s simple:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Read your file into a buffer. const buffer = readFileSync('./runtime_config/common/file.pdf'); // Create the DataTransfer and File const dataTransfer = await scope.page.evaluateHandle((data) => { const dt = new DataTransfer(); // Convert the buffer to a hex array const file = new File([data.toString('hex')], 'file.pdf', { type: 'application/pdf' }); dt.items.add(file); return dt; }, buffer); // Now dispatch await page.dispatchEvent('YOUR_TARGET_SELECTOR', 'drop', { dataTransfer }); |
And if you’re using TypeScript, you’ll need to reference lib.dom
by adding this at the top of your TypeScript file:
1 |
/// <reference lib="dom"/> |