Drag and drop in Playwright
In Playwright, you can perform drag and drop actions using the dragAndDrop
method on an element handle. This method simulates the dragging of an element from one location to another. Below is an example of how to perform drag and drop in Playwright:
Example
Let's assume you have a page with a draggable element and a drop target.
<!DOCTYPE html>
<html>
<head>
<title>Drag and Drop Example</title>
</head>
<body>
<div id="drag-source" draggable="true" style="width: 100px; height: 100px; background-color: blue;"></div>
<div id="drop-target" style="width: 200px; height: 200px; background-color: red; margin-top: 20px;"></div>
<script>
const dragSource = document.getElementById('drag-source');
const dropTarget = document.getElementById('drop-target');
dragSource.addEventListener('dragstart', (event) => {
event.dataTransfer.setData('text/plain', 'This text may be dragged');
});
dropTarget.addEventListener('dragover', (event) => {
event.preventDefault();
});
dropTarget.addEventListener('drop', (event) => {
event.preventDefault();
const data = event.dataTransfer.getData('text');
dropTarget.textContent = data;
});
</script>
</body>
</html>
Playwright Script
Here's how you can perform the drag and drop action using Playwright:
const { chromium } = require('playwright');
(async () => {
// Launch the browser
const browser = await chromium.launch({ headless: false });
const context = await browser.newContext();
const page = await context.newPage();
// Go to the page with the drag and drop example
await page.goto('file:///path/to/your/drag_and_drop_example.html'); // Replace with the actual path to your HTML file
// Locate the source and target elements
const dragSource = await page.$('#drag-source');
const dropTarget = await page.$('#drop-target');
// Perform the drag and drop action
await dragSource.dragAndDrop(dropTarget);
// Close the browser
await browser.close();
})();
In this script:
- We launch a Chromium browser and open a new page.
- We navigate to the local HTML file containing the drag and drop example.
- We locate the source and target elements using the
page.$
method. - We perform the drag and drop action using the
dragAndDrop
method. - We close the browser.
Important Points
- The
dragAndDrop
method is a convenient way to perform drag and drop actions in Playwright. - Ensure the elements you are trying to drag and drop are visible and interactable on the page.
Running the Example
To run the example, make sure you have Playwright installed and save the HTML content to a file (e.g., drag_and_drop_example.html
). Then, run the Playwright script using Node.js.
node your_playwright_script.js
This will open the browser, navigate to the page, perform the drag and drop action, and close the browser.
Published on: Jun 28, 2024, 03:18 AM