Set up Playwright with Perfecto – iOS
To integrate Playwright with Perfecto for iOS testing, follow the prerequisites and setup steps below for your preferred programming language. iOS Playwright support is generally available for real devices running iOS 18 and later through the Node.js SDK (JavaScript and TypeScript), .NET SDK (C#), Python, and Java SDKs. For information on known limitations and unsupported features, see Playwright known limitations.
For information on Playwright overview and prerequisites, see Playwright.
On this page:
Restrictions
The following restrictions apply to iOS Playwright:
-
Status: Generally available as of release 26.12 on real iOS devices running iOS 18 and later provisioned through Perfecto cloud
-
Supported Playwright version: Playwright 1.62 and newer. Pinning to the exact version is required. Other Playwright versions are not supported and will not connect.
-
Available SDKs: Node.js SDK (JavaScript and TypeScript), .NET SDK (C#), Python SDK, and Java SDK.
-
Cloud configuration: Must specify cloud name in WebSocket URL.
Prerequisites
-
A real iOS device provisioned on your Perfecto cloud
-
A Perfecto
securityToken -
The device's
deviceName(UDID), for example00001234-0005ACB12331120E
Mandatory capabilities
| Capability | Value |
|---|---|
platformName
|
'iOS'
|
securityToken
|
your Perfecto security token |
deviceName
|
target device's UDID |
Configuration requirement
The cloud name must be specified in the WebSocket URL used to connect:
wss://{cloudName}.perfectomobile.com/websocket?<encoded capabilities>
Setup steps
Click a language to expand the steps.
-
Install Playwright:
Copynpm install --save-exact --save-dev @playwright/test@1.62 @types/node ts-node
npm install --save-exact playwright@1.62 -
Create a
setup-ios.tsfile that extends Playwright's basetestobject to connect to your Perfecto iOS device instead of launching a local browser:Copyimport { test as base } from '@playwright/test';
import { webkit } from '@playwright/test';
export const test = base.extend({
browser: [async ({}, use) => {
const caps = {
platformName: 'iOS',
securityToken: '<SECURITY_TOKEN>',
deviceName: '<DEVICE_UDID>',
};
const cloudName = 'demo';
const browser = await webkit.connect(
`wss://${cloudName}.perfectomobile.com/websocket?` +
encodeURIComponent(JSON.stringify(caps)),
{ timeout: 90_000 },
);
await use(browser);
await browser.close();
}, { scope: 'worker', timeout: 90_000 }],
page: async ({ browser }, use) => {
const context = await browser.newContext({ hasTouch: true });
const page = await context.newPage();
await use(page);
await page.close();
await context.close();
},
});
export { expect } from '@playwright/test'; -
Import
test/expectfrom yoursetup-ios.tsinstead of@playwright/test, and write a normal Playwright test:Copyimport { test, expect } from './setup-ios';
test('loads the home page', async ({ page }) => {
await page.goto('https://example.com');
await expect(page).toHaveTitle(/Example Domain/);
}); -
Run the test:
Copynpx playwright test --config=playwright.ios.config.ts
-
Install Playwright:
Copynpm install --save-exact playwright@1.62 -
Connect with the
webkitbrowser launcher exported fromplaywright, then run your test:Copyconst { webkit } = require('playwright');
(async () => {
const caps = {
platformName: 'iOS',
securityToken: '<SECURITY_TOKEN>',
deviceName: '<DEVICE_UDID>',
};
const cloudName = 'demo';
const browser = await webkit.connect(
`wss://${cloudName}.perfectomobile.com/websocket?` +
encodeURIComponent(JSON.stringify(caps)),
);
const context = await browser.newContext({ hasTouch: true });
const page = await context.newPage();
await page.goto('https://example.com');
console.log(await page.title());
await page.close();
await context.close();
await browser.close();
})();
Before you begin, make sure you have a real iOS 18 or newer device in your Perfecto cloud, your security token, the device UDID, and the .NET 10 SDK.
-
Create an NUnit project and add Microsoft.Playwright:
Copydotnet new nunit --framework net10.0
dotnet add package Microsoft.Playwright --version 1.62.0You do not need to install browsers because the browser runs on the device. Delete the
UnitTest1.csfile created by the project template. -
Add a
DeviceConnection.csfile with a[SetUpFixture]outside any namespace. The fixture connects once for the test assembly so that all tests share the device connection:Copyusing System.Text.Json;
using Microsoft.Playwright;
[SetUpFixture]
public class DeviceConnection
{
private const string CloudName = "demo";
private static IPlaywright? _playwright;
public static IBrowser Browser { get; private set; } = null!;
[OneTimeSetUp]
public async Task ConnectAsync()
{
var capabilities = new Dictionary<string, string>
{
["platformName"] = "iOS",
["securityToken"] = "<SECURITY_TOKEN>",
["deviceName"] = "<DEVICE_UDID>",
};
var query = Uri.EscapeDataString(JsonSerializer.Serialize(capabilities));
var endpoint = $"wss://{CloudName}.perfectomobile.com/websocket?{query}";
_playwright = await Playwright.CreateAsync();
Browser = await _playwright.Webkit.ConnectAsync(endpoint, new() { Timeout = 90_000 });
}
[OneTimeTearDown]
public async Task DisconnectAsync()
{
await Browser.CloseAsync();
_playwright?.Dispose();
}
}Replace
demo,<SECURITY_TOKEN>, and<DEVICE_UDID>with your cloud name, security token, and device UDID. -
Add an
ExampleTests.csfile. Each test creates a new context and page on the shared browser connection and closes them when the test ends:Copyusing System.Text.RegularExpressions;
using Microsoft.Playwright;
using static Microsoft.Playwright.Assertions;
public class ExampleTests
{
private IBrowserContext _context = null!;
private IPage _page = null!;
[SetUp]
public async Task OpenPageAsync()
{
_context = await DeviceConnection.Browser.NewContextAsync();
_page = await _context.NewPageAsync();
}
[TearDown]
public async Task ClosePageAsync()
{
try
{
await _page.CloseAsync();
}
finally
{
await _context.CloseAsync();
}
}
[Test]
public async Task HasTitle()
{
await _page.GotoAsync("https://playwright.dev/");
await Expect(_page).ToHaveTitleAsync(new Regex("Playwright"));
}
} -
Run the test with NUnit parallel execution disabled because the device serves one session at a time:
Copydotnet test -- NUnit.NumberOfTestWorkers=0
Before you begin, make sure you have a real iOS 18 or later device in your Perfecto cloud, your security token, the device UDID, and Python 3.10 or later.
-
Create a virtual environment, activate it, and install the pinned packages:
Copypython3 -m venv .venv
source .venv/bin/activate
pip install playwright==1.62.0 pytest-playwright==0.10.0On Windows, activate the environment with
.venv\Scripts\activate. You do not need to runplaywright installbecause the browser runs on the device. -
In a
conftest.pyfile, override thebrowserfixture to connect to the Perfecto device once for the test session. Override thepagefixture so each test gets a new context and page:Copyimport json
from urllib.parse import quote
import pytest
CLOUD_NAME = "demo"
CAPABILITIES = {
"platformName": "iOS",
"securityToken": "<SECURITY_TOKEN>",
"deviceName": "<DEVICE_UDID>",
}
@pytest.fixture(scope="session")
def browser(playwright):
capabilities = quote(json.dumps(CAPABILITIES, separators=(",", ":")), safe="")
endpoint = f"wss://{CLOUD_NAME}.perfectomobile.com/websocket?{capabilities}"
browser = playwright.webkit.connect(endpoint, timeout=90_000)
yield browser
browser.close()
@pytest.fixture
def page(browser):
context = browser.new_context()
page = context.new_page()
try:
yield page
finally:
try:
page.close()
finally:
context.close()Replace
demo,<SECURITY_TOKEN>, and<DEVICE_UDID>with your cloud name, security token, and device UDID. -
Add a
test_example.pyfile next toconftest.py. This test opens a URL and checks the page title:Copyimport re
from playwright.sync_api import Page, expect
def test_has_title(page: Page):
page.goto("https://playwright.dev/")
expect(page).to_have_title(re.compile("Playwright")) -
With the virtual environment active, run the test:
Copypytest --browser webkit
Before you begin, make sure you have a real iOS 18 or later device in your Perfecto cloud, your security token, the device UDID, Java 17 or later, and Maven 3.9 or later.
-
Add Playwright, Gson, and JUnit 5 to your
pom.xml. Addmaven-surefire-plugin3.x so Maven can run JUnit 5 tests:Copypom.xml<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>sample-test</artifactId>
<version>1.0.0</version>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- Must match the major.minor of the Playwright server in Perfecto Cloud -->
<dependency>
<groupId>com.microsoft.playwright</groupId>
<artifactId>playwright</artifactId>
<version>1.62.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.15.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.14.4</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.1</version>
</plugin>
</plugins>
</build>
</project> -
Create the Java files in the
src/test/javafolder, relative to the directory that containspom.xml. -
Create a JUnit base class to connect to the device once per test class. It creates a new touch-enabled context and page for each test, then closes the context and connection:
Copyimport com.google.gson.Gson;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
public abstract class PerfectoIosTest {
private static final String CLOUD_NAME = "demo";
private static final Map<String, String> CAPABILITIES = Map.of(
"platformName", "iOS",
"securityToken", "<SECURITY_TOKEN>",
"deviceName", "<DEVICE_UDID>");
private static Playwright playwright;
private static Browser browser;
private BrowserContext context;
protected Page page;
@BeforeAll
static void connect() {
playwright = Playwright.create(new Playwright.CreateOptions()
.setEnv(Map.of("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "1")));
String endpoint = "wss://" + CLOUD_NAME + ".perfectomobile.com/websocket?"
+ URLEncoder.encode(new Gson().toJson(CAPABILITIES), StandardCharsets.UTF_8);
browser = playwright.webkit().connect(endpoint,
new BrowserType.ConnectOptions().setTimeout(90_000));
}
@BeforeEach
void openPage() {
context = browser.newContext(new Browser.NewContextOptions().setHasTouch(true));
page = context.newPage();
}
@AfterEach
void closeContext() {
page.close();
context.close();
}
@AfterAll
static void disconnect() {
browser.close();
playwright.close();
}
}Replace
demo,<SECURITY_TOKEN>, and<DEVICE_UDID>with your cloud name, security token, and device UDID.The
PLAYWRIGHT_SKIP_BROWSER_DOWNLOADenvironment variable prevents Playwright from downloading a local browser because the browser runs on the device. -
Extend
PerfectoIosTestand write a Playwright test. This example opens a URL and checks the page title:Copyimport static com.microsoft.playwright.assertions.PlaywrightAssertions.assertThat;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
class ExampleTest extends PerfectoIosTest {
@Test
void hasTitle() {
page.navigate("https://playwright.dev/");
assertThat(page).hasTitle(Pattern.compile("Playwright"));
}
} -
Run the tests:
Copymvn test
Run without a test framework
You can also connect to the device from a main method. Use the same URL and capabilities to open a page, print its title, and close the context and browser:
import com.google.gson.Gson;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class Example {
public static void main(String[] args) {
Map<String, String> capabilities = Map.of(
"platformName", "iOS",
"securityToken", "<SECURITY_TOKEN>",
"deviceName", "<DEVICE_UDID>");
String endpoint = "wss://demo.perfectomobile.com/websocket?"
+ URLEncoder.encode(new Gson().toJson(capabilities), StandardCharsets.UTF_8);
try (Playwright playwright = Playwright.create(new Playwright.CreateOptions()
.setEnv(Map.of("PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD", "1")))) {
Browser browser = playwright.webkit().connect(endpoint,
new BrowserType.ConnectOptions().setTimeout(90_000));
BrowserContext context = browser.newContext(new Browser.NewContextOptions().setHasTouch(true));
Page page = context.newPage();
page.navigate("https://playwright.dev/");
System.out.println(page.title());
page.close();
context.close();
browser.close();
}
}
}
Replace <SECURITY_TOKEN> and <DEVICE_UDID> with your values. Run the command that matches the location of Example.java from the project root:
-
If
Example.javais insrc/main/javaand the dependencies are outside the test scope, run:Copymvn compile exec:java -Dexec.mainClass=Example -
If
Example.javais insrc/test/javanext to your tests, keep the dependencies in the test scope and run:Copymvn -q test-compile exec:java -Dexec.mainClass=Example -Dexec.classpathScope=test
If Example is in a package, use its full name for exec.mainClass, for example org.example.Example. The program prints the page title and exits.