Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

      July 22, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

      July 22, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

      July 22, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Playwright Mobile Automation for Seamless Web Testing

    Playwright Mobile Automation for Seamless Web Testing

    April 3, 2025

    Playwright is a fast and modern testing framework known for its efficiency and automation capabilities. It is great for web testing, including Playwright Mobile Automation, which provides built-in support for emulating real devices like smartphones and tablets. Features like custom viewports, user agent simulation, touch interactions, and network throttling help create realistic mobile testing environments without extra setup. Unlike Selenium and Appium, which rely on third-party tools, Playwright offers native mobile emulation and faster execution, making it a strong choice for testing web applications on mobile browsers. However, Playwright does not support native app testing for Android or iOS, as it focuses only on web browsers and web views.

    Playwright Mobile Automation

    In this blog, the setup process for mobile web automation in Playwright will be explained in detail. The following key aspects will be covered:

    • Emulating Mobile Devices
    • Using Custom Mobile Viewports
    • Real Device Setup & Execution

    Before proceeding with mobile web automation, it is essential to ensure that Playwright is properly installed on your machine. In this section, a step-by-step guide will be provided to help set up Playwright along with its dependencies. The installation process includes the following steps:

    Setting Up Playwright

    Before starting with mobile web automation, ensure that you have Node.js installed on your system. Playwright requires Node.js to run JavaScript-based automation scripts.

    1. Verify Node.js Installation

    To check if Node.js is installed, open a terminal or command prompt and run:

    node -v
    

    If Node.js is installed, this command will return the installed version. If not, download and install the latest version from the official Node.js website.

    2. Install Playwright and Its Dependencies

    Once Node.js is set up, install Playwright using npm (Node Package Manager) with the following commands:

    
    npm install @playwright/test
    
    npx playwright install
    
    
    • The first command installs the Playwright testing framework.
    • The second command downloads and installs the required browser binaries, including Chromium, Firefox, and WebKit, to enable cross-browser testing.

    3. Verify Playwright Installation

    To ensure that Playwright is installed correctly, you can check its version by running:

    
    npx playwright --version
    
    

    This will return the installed Playwright version, confirming a successful setup.

    4. Initialize a Playwright Test Project (Optional)

    If you plan to use Playwright’s built-in test framework, initialize a test project with:

    
    npx playwright test --init
    
    

    This sets up a basic folder structure with example tests, Playwright configurations, and dependencies.

    Once Playwright is installed and configured, you are ready to start automating mobile web applications. The next step is configuring the test environment for mobile emulation.

    Emulating Mobile Devices

    Playwright provides built-in mobile device emulation, enabling you to test web applications on various popular devices such as Pixel 5, iPhone 12, and Samsung Galaxy S20. This feature ensures that your application behaves consistently across different screen sizes, resolutions, and touch interactions, making it an essential tool for responsive web testing.

    1. Understanding Mobile Device Emulation in Playwright

    Playwright’s device emulation is powered by predefined device profiles, which include settings such as:

    • Viewport size (width and height)
    • User agent string (to simulate mobile browsers)
    • Touch support
    • Device scale factor
    • Network conditions (optional)

    These configurations allow you to mimic real mobile devices without requiring an actual physical device.

    2. Example Code for Emulating a Mobile Device

    Here’s an example script that demonstrates how to use Playwright’s mobile emulation with the Pixel 5 device:

    
    const { test, expect, devices } = require('@playwright/test');
    
    
    // Apply Pixel 5 emulation settings
    
    test.use({ ...devices['Pixel 5'] });
    
    
    test('Verify page title on mobile', async ({ page }) => {
    
        // Navigate to the target website
    
        await page.goto('https://playwright.dev/');
    
    
        // Simulate a short wait time for page load
    
        await page.waitForTimeout(2000);
    
    
        // Capture a screenshot of the mobile view
    
        await page.screenshot({ path: 'pixel5.png' });
    
    
        // Validate the page title to ensure correct loading
    
        await expect(page).toHaveTitle("Fast and reliable end-to-end testing for modern web apps | Playwright");
    
    });
    
    

    3. How This Script Works

    • It imports test, expect, and devices from Playwright.
    • The test.use({…devices[‘Pixel 5’]}) method applies the Pixel 5 emulation settings.
    • The script navigates to the Playwright website.
    • It waits for 2 seconds, simulating real user behavior.
    • A screenshot is captured to visually verify the UI appearance on the Pixel 5 emulation.
    • The script asserts the page title, ensuring that the correct page is loaded.

    4. Running the Script

    Save this script in a test file (e.g., mobile-test.spec.js) and execute it using the following command:

    
    npx playwright test mobile-test.spec.js
    
    

    If Playwright is set up correctly, the test will run in emulation mode and generate a screenshot named pixel5.png in your project folder.

    Playwright Mobile Automation for Seamless Web Testing

    5. Testing on Other Mobile Devices

    To test on different devices, simply change the emulation settings:

    
    test.use({ ...devices['iPhone 12'] }); // Emulates iPhone 12
    
    test.use({ ...devices['Samsung Galaxy S20'] }); // Emulates Samsung Galaxy S20
    
    

    Playwright includes a wide range of device profiles, which can be found by running:

    
    npx playwright devices
    
    

    Using Custom Mobile Viewports

    Playwright provides built-in mobile device emulation, but sometimes your test may require a device that is not available in Playwright’s predefined list. In such cases, you can manually define a custom viewport, user agent, and touch capabilities to accurately simulate the target device.

    1. Why Use Custom Mobile Viewports?

    • Some new or less common mobile devices may not be available in Playwright’s devices list.
    • Custom viewports allow testing on specific screen resolutions and device configurations.
    • They provide flexibility when testing progressive web apps (PWAs) or applications with unique viewport breakpoints.

    2. Example Code for Custom Viewport

    The following Playwright script manually configures a Samsung Galaxy S10 viewport and device properties:

    
    const { test, expect } = require('@playwright/test');
    
    
    test.use({
    
      viewport: { width: 414, height: 896 }, // Samsung Galaxy S10 resolution
    
      userAgent: 'Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Mobile Safari/537.36',
    
      isMobile: true, // Enables mobile-specific behaviors
    
      hasTouch: true  // Simulates touch screen interactions
    
    });
    
    
    test('Open page with custom mobile resolution', async ({ page }) => {
    
        // Navigate to the target webpage
    
        await page.goto('https://playwright.dev/');
    
    
        // Simulate real-world waiting behavior
    
        await page.waitForTimeout(2000);
    
    
        // Capture a screenshot of the webpage
    
        await page.screenshot({ path: 'android_custom.png' });
    
    
        // Validate that the page title is correct
    
        await expect(page).toHaveTitle("Fast and reliable end-to-end testing for modern web apps | Playwright");
    
    });
    
    

    3. How This Script Works

    • viewport: { width: 414, height: 896 } → Sets the screen size to Samsung Galaxy S10 resolution.
    • userAgent: ‘Mozilla/5.0 (Linux; Android 10; SM-G973F)…’ → Spoofs the browser user agent to mimic a real Galaxy S10 browser.
    • isMobile: true → Enables mobile-specific browser behaviors, such as dynamic viewport adjustments.
    • hasTouch: true → Simulates a touchscreen, allowing for swipe and tap interactions.
    • The test navigates to Playwright’s website, waits for 2 seconds, takes a screenshot, and verifies the page title.

    4. Running the Test

    To execute this test, save it in a file (e.g., custom-viewport.spec.js) and run:

    
    npx playwright test custom-viewport.spec.js
    
    

    After execution, a screenshot named android_custom.png will be saved in your project folder.

    Playwright Mobile Automation for Seamless Web Testing

    5. Testing Other Custom Viewports

    You can modify the script to test different resolutions by changing the viewport size and user agent.

    Example: Custom iPad Pro 12.9 Viewport

    
    test.use({
    
      viewport: { width: 1024, height: 1366 },
    
      userAgent: 'Mozilla/5.0 (iPad; CPU OS 14_6 like Mac OS X) AppleWebKit/537.36 (KHTML, like Gecko) Version/14.1.1 Mobile/15E148 Safari/537.36',
    
      isMobile: false, // iPads are often treated as desktops
    
      hasTouch: true
    
    });
    
    

    Example: Low-End Android Device (320×480, Old Android Browser)

    
    test.use({
    
      viewport: { width: 320, height: 480 },
    
      userAgent: 'Mozilla/5.0 (Linux; U; Android 4.2.2; en-us; GT-S7562) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30',
    
      isMobile: true,
    
      hasTouch: true
    
    });
    
    

    Real Device Setup & Execution

    Playwright enables automation testing on real Android devices and emulators using Android Debug Bridge (ADB). This capability allows testers to validate their applications in actual mobile environments, ensuring accurate real-world behavior.

    Unlike Android, Playwright does not currently support real-device testing on iOS due to Apple’s restrictions on third-party browser automation. Safari automation on iOS requires WebDriver-based solutions like Appium or Apple’s XCUITest, as Apple does not provide a direct automation API similar to ADB for Android. However, Playwright’s team is actively working on expanding iOS support through WebKit debugging, but full-fledged real-device automation is still in the early stages.

    Below is a step-by-step guide to setting up and executing Playwright tests on an Android device.

    Preconditions: Setting Up Your Android Device for Testing

    1. Install Android Command-Line Tools

    • Download and install the Android SDK Command-Line Tools from the official Android Developer website.
    • Set up the ANDROID_HOME environment variable and add platform-tools to the system PATH.

    2. Enable USB Debugging on Your Android Device

    • Go to Settings > About Phone > Tap “Build Number” 7 times to enable Developer Mode.
    • Open Developer Options and enable USB Debugging.
    • If using a real device, connect it via USB and authorize debugging when prompted.

    3. Ensure ADB is Installed & Working

    Run the following command to verify that ADB (Android Debug Bridge) detects the connected device:

    
    adb devices
    
    
    Running Playwright Tests on a Real Android Device

    Sample Playwright Script for Android Device Automation

    
    const { _android: android } = require('playwright');
    
    const { expect } = require('@playwright/test');
    
    
    (async () => {
    
      // Get the list of connected Android devices
    
      const devices = await android.devices();
    
      if (devices.length === 0) {
    
        console.log("No Android devices found!");
    
        return;
    
      }
    
    
      // Connect to the first available Android device
    
      const device = devices[0];
    
      console.log(`Connected to: ${device.model()} (Serial: ${device.serial()})`);
    
    
      // Launch the Chrome browser on the Android device
    
      const context = await device.launchBrowser();
    
      console.log('Chrome browser launched!');
    
    
      // Open a new browser page
    
      const page = await context.newPage();
    
      console.log('New page opened!');
    
    
      // Navigate to a website
    
      await page.goto('https://webkit.org/');
    
      console.log('Page loaded!');
    
    
      // Print the current URL
    
      console.log(await page.evaluate(() => window.location.href));
    
    
      // Verify if an element is visible
    
      await expect(page.locator("//h1[contains(text(),'engine')]")).toBeVisible();
    
      console.log('Element found!');
    
    
      // Capture a screenshot of the page
    
      await page.screenshot({ path: 'page.png' });
    
      console.log('Screenshot taken!');
    
    
      // Close the browser session
    
      await context.close();
    
    
      // Disconnect from the device
    
      await device.close();
    
    })();
    
    
    
    

    How the Script Works

    • Retrieves connected Android devices using android.devices().
    • Connects to the first available Android device.
    • Launches Chrome on the Android device and opens a new page.
    • Navigates to https://webkit.org/ and verifies that a page element (e.g., h1 containing “engine”) is visible.
    • Takes a screenshot and saves it as page.png.
    • Closes the browser and disconnects from the device.

    Executing the Playwright Android Test

    To run the test, save the script as android-test.js and execute it using:

    
    node android-test.js
    
    

    If the setup is correct, the test will launch Chrome on the Android device, navigate to the webpage, validate elements, and capture a screenshot.

    Screenshot saved from real device

    Playwright Mobile Automation for Seamless Web Testing

    Frequently Asked Questions

    • What browsers does Playwright support for mobile automation?

      Playwright supports Chromium, Firefox, and WebKit, allowing comprehensive mobile web testing across different browsers.

    • Can Playwright test mobile web applications in different network conditions?

      Yes, Playwright allows network throttling to simulate slow connections like 3G, 4G, or offline mode, helping testers verify web application performance under various conditions.

    • Is Playwright the best tool for mobile web automation?

      Playwright is one of the best tools for mobile web testing due to its speed, efficiency, and cross-browser support. However, if you need to test native or hybrid mobile apps, Appium or native testing frameworks are better suited.

    • Does Playwright support real device testing for mobile automation?

      Playwright supports real device testing on Android using ADB, but it does not support native iOS testing due to Apple’s restrictions. For iOS testing, alternative solutions like Appium or XCUITest are required.

    • Does Playwright support mobile geolocation testing?

      Yes, Playwright allows testers to simulate GPS locations to verify how web applications behave based on different geolocations. This is useful for testing location-based services like maps and delivery apps.

    • Can Playwright be integrated with CI/CD pipelines for mobile automation?

      Yes, Playwright supports CI/CD integration with tools like Jenkins, GitHub Actions, GitLab CI, and Azure DevOps, allowing automated mobile web tests to run on every code deployment.

    The post Playwright Mobile Automation for Seamless Web Testing appeared first on Codoid.

    Source: Read More

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleWhy Can’t I Locate Clickable Element in Choose File Keyword?
    Next Article Researchers from Dataocean AI and Tsinghua University Introduces Dolphin: A Multilingual Automatic Speech Recognition ASR Model Optimized for Eastern Languages and Dialects

    Related Posts

    Development

    GPT-5 is Coming: Revolutionizing Software Testing

    July 22, 2025
    Development

    Win the Accessibility Game: Combining AI with Human Judgment

    July 22, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    Google Ends Remote Work for Many: Return to Office or Leave

    Security

    Photonic processor could streamline 6G wireless signal processing

    Artificial Intelligence

    Is HR ready for AI?

    News & Updates

    Samsung launches One UI 8 beta – what’s new and how to join

    News & Updates

    Highlights

    CVE-2025-44612 – Tinxy WiFi Lock Controller Remote Information Disclosure

    May 30, 2025

    CVE ID : CVE-2025-44612

    Published : May 30, 2025, 3:15 a.m. | 1 hour, 48 minutes ago

    Description : Tinxy WiFi Lock Controller v1 RF was discovered to transmit sensitive information in plaintext, including control information and device credentials, allowing attackers to possibly intercept and access sensitive information via a man-in-the-middle attack.

    Severity: 0.0 | NA

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    You can track the top AI image generators via this new leaderboard – and vote for your favorite too

    June 5, 2025

    Microsoft Defender Spoofing Vulnerability Allows Privilege Escalation and AD Access

    June 13, 2025

    CVE-2025-4156 – PHPGurukul Boat Booking System SQL Injection Vulnerability

    May 1, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.