Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .github/workflows/tests_webview_simulator.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
name: "tests WebView (iOS Simulator)"

on:
# pull_request trigger disabled to avoid CI churn during wk_wv iteration - restore before merge

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

env:
FORCE_COLOR: 1
ELECTRON_SKIP_BINARY_DOWNLOAD: 1

jobs:
test_webview_simulator:
name: "WebView on iOS Simulator (${{ matrix.shard }}/4)"
runs-on: macos-15
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Runner environment
run: |
echo "::group::OS / Xcode"
sw_vers
uname -a
xcode-select -p
xcodebuild -version
echo "::endgroup::"
echo "::group::Available iOS runtimes"
xcrun simctl list runtimes
echo "::endgroup::"
echo "::group::Available device types"
xcrun simctl list devicetypes | grep -i 'iPhone\|iPad' | head -40
echo "::endgroup::"
echo "::group::Network config"
cat /etc/hosts
ifconfig lo0
echo "::endgroup::"

- name: Ensure ::1 localhost in /etc/hosts
run: |
if grep -qE '^::1[[:space:]]+localhost' /etc/hosts; then
echo "::1 localhost already present"
else
echo "::1 localhost" | sudo tee -a /etc/hosts
echo "Added ::1 localhost"
fi
echo "--- /etc/hosts after ---"
cat /etc/hosts

- name: npm ci
run: |
echo "::group::npm ci"
npm ci
echo "::endgroup::"

- name: npm run build
run: |
echo "::group::npm run build"
npm run build
echo "::endgroup::"

- name: Install ios-webkit-debug-proxy
run: |
echo "::group::brew install ios-webkit-debug-proxy"
brew install ios-webkit-debug-proxy
which ios_webkit_debug_proxy
ios_webkit_debug_proxy --help 2>&1 | head -40 || true
echo "::endgroup::"

- name: Boot iOS Simulator
uses: futureware-tech/simulator-action@v5
with:
# Per wiki/Devices-macos-15.md only iPhone 16/17 series ship pre-installed; iPhone 15 isn't.
model: 'iPhone 16'
os_version: '18.6'
wait_for_boot: true
boot_timeout_seconds: 300

- name: Simulator state after boot
run: |
echo "::group::Booted devices"
xcrun simctl list devices booted
echo "::endgroup::"
echo "::group::Simulator processes"
pgrep -lf Simulator || true
pgrep -lf launchd_sim || true
echo "::endgroup::"

- name: Locate simulator webinspectord socket
run: |
echo "::group::Locating com.apple.webinspectord_sim.socket"
# On modern macOS, ios_webkit_debug_proxy can no longer auto-discover the simulator;
# we have to point -s at the launchd-owned unix socket.
for i in $(seq 1 15); do
SOCK=$(lsof -aUc launchd_sim 2>/dev/null | awk '/com\.apple\.webinspectord_sim\.socket/{print $NF; exit}')
[[ -n "$SOCK" ]] && break
echo "attempt $i: socket not found yet"
sleep 1
done
if [[ -z "$SOCK" ]]; then
echo "Failed to locate webinspectord_sim.socket"
echo "--- launchd_sim file table ---"
lsof -aUc launchd_sim 2>/dev/null || true
exit 1
fi
echo "socket: $SOCK"
echo "SIM_WI_SOCKET=unix:$SOCK" >> $GITHUB_ENV
echo "::endgroup::"

- name: Start ios-webkit-debug-proxy
run: |
echo "::group::Starting proxy (SIM_WI_SOCKET=$SIM_WI_SOCKET)"
ios_webkit_debug_proxy -F -d -s "$SIM_WI_SOCKET" -c "null:9221,:9222-9322" > "$RUNNER_TEMP/iwdp.log" 2>&1 &
PID=$!
echo "IWDP_PID=$PID" >> $GITHUB_ENV
echo "proxy pid=$PID"
sleep 3
if ! kill -0 "$PID" 2>/dev/null; then
echo "Proxy died immediately. Log:"
cat "$RUNNER_TEMP/iwdp.log"
exit 1
fi
echo "::endgroup::"
echo "::group::Listening ports"
lsof -nP -iTCP -sTCP:LISTEN | grep -E "9221|9222|ios_webkit" || true
echo "::endgroup::"

- name: Run WebView tests
run: |
echo "::group::Test run (shard ${{ matrix.shard }}/4)"
npx playwright test --config tests/webview/playwright.config.ts --shard=${{ matrix.shard }}/4
echo "::endgroup::"

- name: Stop proxy
if: always()
run: |
[[ -n "$IWDP_PID" ]] && kill "$IWDP_PID" 2>/dev/null || true
# Simulator shutdown is owned by futureware-tech/simulator-action's post step.

- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: webview-simulator-logs-${{ matrix.shard }}
path: |
${{ github.workspace }}/test-results/**
if-no-files-found: ignore
1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
"ctest": "playwright test --config=tests/library/playwright.config.ts --project=chromium-*",
"ftest": "playwright test --config=tests/library/playwright.config.ts --project=firefox-*",
"wtest": "playwright test --config=tests/library/playwright.config.ts --project=webkit-*",
"wvtest": "playwright test --config=tests/webview/playwright.config.ts",
"atest": "playwright test --config=tests/android/playwright.config.ts",
"etest": "playwright test --config=tests/electron/playwright.config.ts",
"itest": "playwright test --config=tests/installation/playwright.config.ts",
Expand Down
5 changes: 3 additions & 2 deletions packages/injected/src/injectedScript.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1112,8 +1112,9 @@ export class InjectedScript {
return;

// Playwright only issues trusted events, so allow any custom events originating from
// the page or content scripts.
if (!event.isTrusted)
// the page or content scripts. The WebView backend cannot produce trusted events, so
// it marks synthetic events with __pwTrustedSynthetic to opt back into interception.
if (!event.isTrusted && !(event as any).__pwTrustedSynthetic)
return;

// Determine the event point. Note that Firefox does not always have window.TouchEvent.
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright-core/src/client/browserType.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -150,8 +150,8 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
}

async _connectOverCDP(endpointURL: string, params: api.ConnectOverCDPOptions = {}): Promise<Browser> {
if (this.name() !== 'chromium')
throw new Error('Connecting over CDP is only supported in Chromium.');
if (this.name() !== 'chromium' && this.name() !== 'webkit')
throw new Error('Connecting over CDP is only supported in Chromium and WebKit.');
const headers = params.headers ? headersObjectToArray(params.headers) : undefined;
const result = await this._channel.connectOverCDP({
endpointURL,
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright-core/src/server/webkit/DEPS.list
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
[*]
@isomorphic/**
@utils/**
../
../registry/
node_modules/jpeg-js
node_modules/pngjs

[webkit.ts]
./webview/wvBrowser.ts
9 changes: 8 additions & 1 deletion packages/playwright-core/src/server/webkit/webkit.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,11 +20,14 @@ import path from 'path';
import { wrapInASCIIBox } from '@utils/ascii';
import { spawnAsync } from '@utils/spawnAsync';
import { kBrowserCloseMessageId } from './wkConnection';
import { Browser } from '../browser';
import { BrowserType, kNoXServerRunningError } from '../browserType';
import { WKBrowser } from '../webkit/wkBrowser';
import { WKBrowser } from './wkBrowser';
import { connectOverRDP } from './webview/wvBrowser';

import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
import type { Progress } from '../progress';
import type { ConnectionTransport } from '../transport';
import type * as types from '../types';

Expand All@@ -37,6 +40,10 @@ export class WebKit extends BrowserType {
return WKBrowser.connect(this.attribution.playwright, transport, options);
}

override async connectOverCDP(progress: Progress, endpointURL: string, options: { slowMo?: number, headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean }): Promise<Browser> {
return connectOverRDP(progress, this, endpointURL, options);
}

override amendEnvironment(env: NodeJS.ProcessEnv, userDataDir: string, isPersistent: boolean, options: types.LaunchOptions): NodeJS.ProcessEnv {
return {
...env,
Expand Down
146 changes: 146 additions & 0 deletions packages/playwright-core/src/server/webkit/webview/dialogBridge.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { debugLogger } from '@utils/debugLogger';
import { createHttpServer } from '@utils/network';

import type { IncomingMessage, Server, ServerResponse } from 'http';

export type DialogRequest = {
type: 'alert' | 'confirm' | 'prompt';
message: string;
defaultValue: string;
};

export type DialogResult = {
accept: boolean;
promptText?: string;
};

type DialogHandler = (req: DialogRequest) => Promise<DialogResult>;

export class DialogBridge {
private readonly _server: Server;
private readonly _baseUrl: string;
private readonly _handlers = new Map<string, DialogHandler>();

static async start(): Promise<DialogBridge> {
const server = createHttpServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string')
throw new Error('DialogBridge: failed to bind HTTP server');
return new DialogBridge(server, `http://127.0.0.1:${address.port}`);
}

private constructor(server: Server, baseUrl: string) {
this._server = server;
this._baseUrl = baseUrl;
this._server.on('request', (req, res) => this._handleRequest(req, res));
}

endpointFor(pageId: string): string {
return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`;
}

registerTab(pageId: string, handler: DialogHandler): void {
this._handlers.set(pageId, handler);
}

unregisterTab(pageId: string): void {
this._handlers.delete(pageId);
}

async close(): Promise<void> {
this._handlers.clear();
await new Promise<void>(resolve => this._server.close(() => resolve()));
}

private _writeCorsHeaders(res: ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
}

private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
this._writeCorsHeaders(res);

if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}

const url = new URL(req.url || '/', this._baseUrl);
if (!(req.method === 'POST' && url.pathname === '/dialog')) {
res.statusCode = 404;
res.end();
return;
}

const tab = url.searchParams.get('tab') || '';
const handler = this._handlers.get(tab);
if (!handler) {
// Either the tab is gone or the page raced ahead of registerTab. Reply
// 404 so the page-side override silently falls through.
res.statusCode = 404;
res.end();
return;
}

let body = '';
req.setEncoding('utf8');
req.on('data', chunk => { body += chunk; });
req.on('end', async () => {
let parsed: DialogRequest;
try {
const json = JSON.parse(body);
if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt')
throw new Error(`Invalid dialog type: ${json.type}`);
parsed = {
type: json.type,
message: typeof json.message === 'string' ? json.message : '',
defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '',
};
} catch (e) {
debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`);
res.statusCode = 400;
res.end();
return;
}

try {
const result = await handler(parsed);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
accept: !!result.accept,
promptText: result.promptText,
}));
} catch (e) {
debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`);
res.statusCode = 500;
res.end();
}
});
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
chore: wk_webview experiment by pavelfeldman · Pull Request #41010 · microsoft/playwright · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .github/workflows/tests_webview_simulator.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
name: "tests WebView (iOS Simulator)"

on:
# pull_request trigger disabled to avoid CI churn during wk_wv iteration - restore before merge

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

env:
FORCE_COLOR: 1
ELECTRON_SKIP_BINARY_DOWNLOAD: 1

jobs:
test_webview_simulator:
name: "WebView on iOS Simulator (${{ matrix.shard }}/4)"
runs-on: macos-15
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Runner environment
run: |
echo "::group::OS / Xcode"
sw_vers
uname -a
xcode-select -p
xcodebuild -version
echo "::endgroup::"
echo "::group::Available iOS runtimes"
xcrun simctl list runtimes
echo "::endgroup::"
echo "::group::Available device types"
xcrun simctl list devicetypes | grep -i 'iPhone\|iPad' | head -40
echo "::endgroup::"
echo "::group::Network config"
cat /etc/hosts
ifconfig lo0
echo "::endgroup::"

- name: Ensure ::1 localhost in /etc/hosts
run: |
if grep -qE '^::1[[:space:]]+localhost' /etc/hosts; then
echo "::1 localhost already present"
else
echo "::1 localhost" | sudo tee -a /etc/hosts
echo "Added ::1 localhost"
fi
echo "--- /etc/hosts after ---"
cat /etc/hosts

- name: npm ci
run: |
echo "::group::npm ci"
npm ci
echo "::endgroup::"

- name: npm run build
run: |
echo "::group::npm run build"
npm run build
echo "::endgroup::"

- name: Install ios-webkit-debug-proxy
run: |
echo "::group::brew install ios-webkit-debug-proxy"
brew install ios-webkit-debug-proxy
which ios_webkit_debug_proxy
ios_webkit_debug_proxy --help 2>&1 | head -40 || true
echo "::endgroup::"

- name: Boot iOS Simulator
uses: futureware-tech/simulator-action@v5
with:
# Per wiki/Devices-macos-15.md only iPhone 16/17 series ship pre-installed; iPhone 15 isn't.
model: 'iPhone 16'
os_version: '18.6'
wait_for_boot: true
boot_timeout_seconds: 300

- name: Simulator state after boot
run: |
echo "::group::Booted devices"
xcrun simctl list devices booted
echo "::endgroup::"
echo "::group::Simulator processes"
pgrep -lf Simulator || true
pgrep -lf launchd_sim || true
echo "::endgroup::"

- name: Locate simulator webinspectord socket
run: |
echo "::group::Locating com.apple.webinspectord_sim.socket"
# On modern macOS, ios_webkit_debug_proxy can no longer auto-discover the simulator;
# we have to point -s at the launchd-owned unix socket.
for i in $(seq 1 15); do
SOCK=$(lsof -aUc launchd_sim 2>/dev/null | awk '/com\.apple\.webinspectord_sim\.socket/{print $NF; exit}')
[[ -n "$SOCK" ]] && break
echo "attempt $i: socket not found yet"
sleep 1
done
if [[ -z "$SOCK" ]]; then
echo "Failed to locate webinspectord_sim.socket"
echo "--- launchd_sim file table ---"
lsof -aUc launchd_sim 2>/dev/null || true
exit 1
fi
echo "socket: $SOCK"
echo "SIM_WI_SOCKET=unix:$SOCK" >> $GITHUB_ENV
echo "::endgroup::"

- name: Start ios-webkit-debug-proxy
run: |
echo "::group::Starting proxy (SIM_WI_SOCKET=$SIM_WI_SOCKET)"
ios_webkit_debug_proxy -F -d -s "$SIM_WI_SOCKET" -c "null:9221,:9222-9322" > "$RUNNER_TEMP/iwdp.log" 2>&1 &
PID=$!
echo "IWDP_PID=$PID" >> $GITHUB_ENV
echo "proxy pid=$PID"
sleep 3
if ! kill -0 "$PID" 2>/dev/null; then
echo "Proxy died immediately. Log:"
cat "$RUNNER_TEMP/iwdp.log"
exit 1
fi
echo "::endgroup::"
echo "::group::Listening ports"
lsof -nP -iTCP -sTCP:LISTEN | grep -E "9221|9222|ios_webkit" || true
echo "::endgroup::"

- name: Run WebView tests
run: |
echo "::group::Test run (shard ${{ matrix.shard }}/4)"
npx playwright test --config tests/webview/playwright.config.ts --shard=${{ matrix.shard }}/4
echo "::endgroup::"

- name: Stop proxy
if: always()
run: |
[[ -n "$IWDP_PID" ]] && kill "$IWDP_PID" 2>/dev/null || true
# Simulator shutdown is owned by futureware-tech/simulator-action's post step.

- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: webview-simulator-logs-${{ matrix.shard }}
path: |
${{ github.workspace }}/test-results/**
if-no-files-found: ignore
1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
"ctest": "playwright test --config=tests/library/playwright.config.ts --project=chromium-*",
"ftest": "playwright test --config=tests/library/playwright.config.ts --project=firefox-*",
"wtest": "playwright test --config=tests/library/playwright.config.ts --project=webkit-*",
"wvtest": "playwright test --config=tests/webview/playwright.config.ts",
"atest": "playwright test --config=tests/android/playwright.config.ts",
"etest": "playwright test --config=tests/electron/playwright.config.ts",
"itest": "playwright test --config=tests/installation/playwright.config.ts",
Expand Down
5 changes: 3 additions & 2 deletions packages/injected/src/injectedScript.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1112,8 +1112,9 @@ export class InjectedScript {
return;

// Playwright only issues trusted events, so allow any custom events originating from
// the page or content scripts.
if (!event.isTrusted)
// the page or content scripts. The WebView backend cannot produce trusted events, so
// it marks synthetic events with __pwTrustedSynthetic to opt back into interception.
if (!event.isTrusted && !(event as any).__pwTrustedSynthetic)
return;

// Determine the event point. Note that Firefox does not always have window.TouchEvent.
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright-core/src/client/browserType.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -150,8 +150,8 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
}

async _connectOverCDP(endpointURL: string, params: api.ConnectOverCDPOptions = {}): Promise<Browser> {
if (this.name() !== 'chromium')
throw new Error('Connecting over CDP is only supported in Chromium.');
if (this.name() !== 'chromium' && this.name() !== 'webkit')
throw new Error('Connecting over CDP is only supported in Chromium and WebKit.');
const headers = params.headers ? headersObjectToArray(params.headers) : undefined;
const result = await this._channel.connectOverCDP({
endpointURL,
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright-core/src/server/webkit/DEPS.list
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
[*]
@isomorphic/**
@utils/**
../
../registry/
node_modules/jpeg-js
node_modules/pngjs

[webkit.ts]
./webview/wvBrowser.ts
9 changes: 8 additions & 1 deletion packages/playwright-core/src/server/webkit/webkit.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,11 +20,14 @@ import path from 'path';
import { wrapInASCIIBox } from '@utils/ascii';
import { spawnAsync } from '@utils/spawnAsync';
import { kBrowserCloseMessageId } from './wkConnection';
import { Browser } from '../browser';
import { BrowserType, kNoXServerRunningError } from '../browserType';
import { WKBrowser } from '../webkit/wkBrowser';
import { WKBrowser } from './wkBrowser';
import { connectOverRDP } from './webview/wvBrowser';

import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
import type { Progress } from '../progress';
import type { ConnectionTransport } from '../transport';
import type * as types from '../types';

Expand All@@ -37,6 +40,10 @@ export class WebKit extends BrowserType {
return WKBrowser.connect(this.attribution.playwright, transport, options);
}

override async connectOverCDP(progress: Progress, endpointURL: string, options: { slowMo?: number, headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean }): Promise<Browser> {
return connectOverRDP(progress, this, endpointURL, options);
}

override amendEnvironment(env: NodeJS.ProcessEnv, userDataDir: string, isPersistent: boolean, options: types.LaunchOptions): NodeJS.ProcessEnv {
return {
...env,
Expand Down
146 changes: 146 additions & 0 deletions packages/playwright-core/src/server/webkit/webview/dialogBridge.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { debugLogger } from '@utils/debugLogger';
import { createHttpServer } from '@utils/network';

import type { IncomingMessage, Server, ServerResponse } from 'http';

export type DialogRequest = {
type: 'alert' | 'confirm' | 'prompt';
message: string;
defaultValue: string;
};

export type DialogResult = {
accept: boolean;
promptText?: string;
};

type DialogHandler = (req: DialogRequest) => Promise<DialogResult>;

export class DialogBridge {
private readonly _server: Server;
private readonly _baseUrl: string;
private readonly _handlers = new Map<string, DialogHandler>();

static async start(): Promise<DialogBridge> {
const server = createHttpServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string')
throw new Error('DialogBridge: failed to bind HTTP server');
return new DialogBridge(server, `http://127.0.0.1:${address.port}`);
}

private constructor(server: Server, baseUrl: string) {
this._server = server;
this._baseUrl = baseUrl;
this._server.on('request', (req, res) => this._handleRequest(req, res));
}

endpointFor(pageId: string): string {
return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`;
}

registerTab(pageId: string, handler: DialogHandler): void {
this._handlers.set(pageId, handler);
}

unregisterTab(pageId: string): void {
this._handlers.delete(pageId);
}

async close(): Promise<void> {
this._handlers.clear();
await new Promise<void>(resolve => this._server.close(() => resolve()));
}

private _writeCorsHeaders(res: ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
}

private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
this._writeCorsHeaders(res);

if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}

const url = new URL(req.url || '/', this._baseUrl);
if (!(req.method === 'POST' && url.pathname === '/dialog')) {
res.statusCode = 404;
res.end();
return;
}

const tab = url.searchParams.get('tab') || '';
const handler = this._handlers.get(tab);
if (!handler) {
// Either the tab is gone or the page raced ahead of registerTab. Reply
// 404 so the page-side override silently falls through.
res.statusCode = 404;
res.end();
return;
}

let body = '';
req.setEncoding('utf8');
req.on('data', chunk => { body += chunk; });
req.on('end', async () => {
let parsed: DialogRequest;
try {
const json = JSON.parse(body);
if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt')
throw new Error(`Invalid dialog type: ${json.type}`);
parsed = {
type: json.type,
message: typeof json.message === 'string' ? json.message : '',
defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '',
};
} catch (e) {
debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`);
res.statusCode = 400;
res.end();
return;
}

try {
const result = await handler(parsed);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
accept: !!result.accept,
promptText: result.promptText,
}));
} catch (e) {
debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`);
res.statusCode = 500;
res.end();
}
});
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' chore: wk_webview experiment by pavelfeldman · Pull Request #41010 · microsoft/playwright · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .github/workflows/tests_webview_simulator.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
name: "tests WebView (iOS Simulator)"

on:
# pull_request trigger disabled to avoid CI churn during wk_wv iteration - restore before merge

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

env:
FORCE_COLOR: 1
ELECTRON_SKIP_BINARY_DOWNLOAD: 1

jobs:
test_webview_simulator:
name: "WebView on iOS Simulator (${{ matrix.shard }}/4)"
runs-on: macos-15
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Runner environment
run: |
echo "::group::OS / Xcode"
sw_vers
uname -a
xcode-select -p
xcodebuild -version
echo "::endgroup::"
echo "::group::Available iOS runtimes"
xcrun simctl list runtimes
echo "::endgroup::"
echo "::group::Available device types"
xcrun simctl list devicetypes | grep -i 'iPhone\|iPad' | head -40
echo "::endgroup::"
echo "::group::Network config"
cat /etc/hosts
ifconfig lo0
echo "::endgroup::"

- name: Ensure ::1 localhost in /etc/hosts
run: |
if grep -qE '^::1[[:space:]]+localhost' /etc/hosts; then
echo "::1 localhost already present"
else
echo "::1 localhost" | sudo tee -a /etc/hosts
echo "Added ::1 localhost"
fi
echo "--- /etc/hosts after ---"
cat /etc/hosts

- name: npm ci
run: |
echo "::group::npm ci"
npm ci
echo "::endgroup::"

- name: npm run build
run: |
echo "::group::npm run build"
npm run build
echo "::endgroup::"

- name: Install ios-webkit-debug-proxy
run: |
echo "::group::brew install ios-webkit-debug-proxy"
brew install ios-webkit-debug-proxy
which ios_webkit_debug_proxy
ios_webkit_debug_proxy --help 2>&1 | head -40 || true
echo "::endgroup::"

- name: Boot iOS Simulator
uses: futureware-tech/simulator-action@v5
with:
# Per wiki/Devices-macos-15.md only iPhone 16/17 series ship pre-installed; iPhone 15 isn't.
model: 'iPhone 16'
os_version: '18.6'
wait_for_boot: true
boot_timeout_seconds: 300

- name: Simulator state after boot
run: |
echo "::group::Booted devices"
xcrun simctl list devices booted
echo "::endgroup::"
echo "::group::Simulator processes"
pgrep -lf Simulator || true
pgrep -lf launchd_sim || true
echo "::endgroup::"

- name: Locate simulator webinspectord socket
run: |
echo "::group::Locating com.apple.webinspectord_sim.socket"
# On modern macOS, ios_webkit_debug_proxy can no longer auto-discover the simulator;
# we have to point -s at the launchd-owned unix socket.
for i in $(seq 1 15); do
SOCK=$(lsof -aUc launchd_sim 2>/dev/null | awk '/com\.apple\.webinspectord_sim\.socket/{print $NF; exit}')
[[ -n "$SOCK" ]] && break
echo "attempt $i: socket not found yet"
sleep 1
done
if [[ -z "$SOCK" ]]; then
echo "Failed to locate webinspectord_sim.socket"
echo "--- launchd_sim file table ---"
lsof -aUc launchd_sim 2>/dev/null || true
exit 1
fi
echo "socket: $SOCK"
echo "SIM_WI_SOCKET=unix:$SOCK" >> $GITHUB_ENV
echo "::endgroup::"

- name: Start ios-webkit-debug-proxy
run: |
echo "::group::Starting proxy (SIM_WI_SOCKET=$SIM_WI_SOCKET)"
ios_webkit_debug_proxy -F -d -s "$SIM_WI_SOCKET" -c "null:9221,:9222-9322" > "$RUNNER_TEMP/iwdp.log" 2>&1 &
PID=$!
echo "IWDP_PID=$PID" >> $GITHUB_ENV
echo "proxy pid=$PID"
sleep 3
if ! kill -0 "$PID" 2>/dev/null; then
echo "Proxy died immediately. Log:"
cat "$RUNNER_TEMP/iwdp.log"
exit 1
fi
echo "::endgroup::"
echo "::group::Listening ports"
lsof -nP -iTCP -sTCP:LISTEN | grep -E "9221|9222|ios_webkit" || true
echo "::endgroup::"

- name: Run WebView tests
run: |
echo "::group::Test run (shard ${{ matrix.shard }}/4)"
npx playwright test --config tests/webview/playwright.config.ts --shard=${{ matrix.shard }}/4
echo "::endgroup::"

- name: Stop proxy
if: always()
run: |
[[ -n "$IWDP_PID" ]] && kill "$IWDP_PID" 2>/dev/null || true
# Simulator shutdown is owned by futureware-tech/simulator-action's post step.

- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: webview-simulator-logs-${{ matrix.shard }}
path: |
${{ github.workspace }}/test-results/**
if-no-files-found: ignore
1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
"ctest": "playwright test --config=tests/library/playwright.config.ts --project=chromium-*",
"ftest": "playwright test --config=tests/library/playwright.config.ts --project=firefox-*",
"wtest": "playwright test --config=tests/library/playwright.config.ts --project=webkit-*",
"wvtest": "playwright test --config=tests/webview/playwright.config.ts",
"atest": "playwright test --config=tests/android/playwright.config.ts",
"etest": "playwright test --config=tests/electron/playwright.config.ts",
"itest": "playwright test --config=tests/installation/playwright.config.ts",
Expand Down
5 changes: 3 additions & 2 deletions packages/injected/src/injectedScript.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1112,8 +1112,9 @@ export class InjectedScript {
return;

// Playwright only issues trusted events, so allow any custom events originating from
// the page or content scripts.
if (!event.isTrusted)
// the page or content scripts. The WebView backend cannot produce trusted events, so
// it marks synthetic events with __pwTrustedSynthetic to opt back into interception.
if (!event.isTrusted && !(event as any).__pwTrustedSynthetic)
return;

// Determine the event point. Note that Firefox does not always have window.TouchEvent.
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright-core/src/client/browserType.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -150,8 +150,8 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
}

async _connectOverCDP(endpointURL: string, params: api.ConnectOverCDPOptions = {}): Promise<Browser> {
if (this.name() !== 'chromium')
throw new Error('Connecting over CDP is only supported in Chromium.');
if (this.name() !== 'chromium' && this.name() !== 'webkit')
throw new Error('Connecting over CDP is only supported in Chromium and WebKit.');
const headers = params.headers ? headersObjectToArray(params.headers) : undefined;
const result = await this._channel.connectOverCDP({
endpointURL,
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright-core/src/server/webkit/DEPS.list
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
[*]
@isomorphic/**
@utils/**
../
../registry/
node_modules/jpeg-js
node_modules/pngjs

[webkit.ts]
./webview/wvBrowser.ts
9 changes: 8 additions & 1 deletion packages/playwright-core/src/server/webkit/webkit.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,11 +20,14 @@ import path from 'path';
import { wrapInASCIIBox } from '@utils/ascii';
import { spawnAsync } from '@utils/spawnAsync';
import { kBrowserCloseMessageId } from './wkConnection';
import { Browser } from '../browser';
import { BrowserType, kNoXServerRunningError } from '../browserType';
import { WKBrowser } from '../webkit/wkBrowser';
import { WKBrowser } from './wkBrowser';
import { connectOverRDP } from './webview/wvBrowser';

import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
import type { Progress } from '../progress';
import type { ConnectionTransport } from '../transport';
import type * as types from '../types';

Expand All@@ -37,6 +40,10 @@ export class WebKit extends BrowserType {
return WKBrowser.connect(this.attribution.playwright, transport, options);
}

override async connectOverCDP(progress: Progress, endpointURL: string, options: { slowMo?: number, headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean }): Promise<Browser> {
return connectOverRDP(progress, this, endpointURL, options);
}

override amendEnvironment(env: NodeJS.ProcessEnv, userDataDir: string, isPersistent: boolean, options: types.LaunchOptions): NodeJS.ProcessEnv {
return {
...env,
Expand Down
146 changes: 146 additions & 0 deletions packages/playwright-core/src/server/webkit/webview/dialogBridge.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { debugLogger } from '@utils/debugLogger';
import { createHttpServer } from '@utils/network';

import type { IncomingMessage, Server, ServerResponse } from 'http';

export type DialogRequest = {
type: 'alert' | 'confirm' | 'prompt';
message: string;
defaultValue: string;
};

export type DialogResult = {
accept: boolean;
promptText?: string;
};

type DialogHandler = (req: DialogRequest) => Promise<DialogResult>;

export class DialogBridge {
private readonly _server: Server;
private readonly _baseUrl: string;
private readonly _handlers = new Map<string, DialogHandler>();

static async start(): Promise<DialogBridge> {
const server = createHttpServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string')
throw new Error('DialogBridge: failed to bind HTTP server');
return new DialogBridge(server, `http://127.0.0.1:${address.port}`);
}

private constructor(server: Server, baseUrl: string) {
this._server = server;
this._baseUrl = baseUrl;
this._server.on('request', (req, res) => this._handleRequest(req, res));
}

endpointFor(pageId: string): string {
return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`;
}

registerTab(pageId: string, handler: DialogHandler): void {
this._handlers.set(pageId, handler);
}

unregisterTab(pageId: string): void {
this._handlers.delete(pageId);
}

async close(): Promise<void> {
this._handlers.clear();
await new Promise<void>(resolve => this._server.close(() => resolve()));
}

private _writeCorsHeaders(res: ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
}

private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
this._writeCorsHeaders(res);

if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}

const url = new URL(req.url || '/', this._baseUrl);
if (!(req.method === 'POST' && url.pathname === '/dialog')) {
res.statusCode = 404;
res.end();
return;
}

const tab = url.searchParams.get('tab') || '';
const handler = this._handlers.get(tab);
if (!handler) {
// Either the tab is gone or the page raced ahead of registerTab. Reply
// 404 so the page-side override silently falls through.
res.statusCode = 404;
res.end();
return;
}

let body = '';
req.setEncoding('utf8');
req.on('data', chunk => { body += chunk; });
req.on('end', async () => {
let parsed: DialogRequest;
try {
const json = JSON.parse(body);
if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt')
throw new Error(`Invalid dialog type: ${json.type}`);
parsed = {
type: json.type,
message: typeof json.message === 'string' ? json.message : '',
defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '',
};
} catch (e) {
debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`);
res.statusCode = 400;
res.end();
return;
}

try {
const result = await handler(parsed);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
accept: !!result.accept,
promptText: result.promptText,
}));
} catch (e) {
debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`);
res.statusCode = 500;
res.end();
}
});
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' chore: wk_webview experiment by pavelfeldman · Pull Request #41010 · microsoft/playwright · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .github/workflows/tests_webview_simulator.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
name: "tests WebView (iOS Simulator)"

on:
# pull_request trigger disabled to avoid CI churn during wk_wv iteration - restore before merge

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

env:
FORCE_COLOR: 1
ELECTRON_SKIP_BINARY_DOWNLOAD: 1

jobs:
test_webview_simulator:
name: "WebView on iOS Simulator (${{ matrix.shard }}/4)"
runs-on: macos-15
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Runner environment
run: |
echo "::group::OS / Xcode"
sw_vers
uname -a
xcode-select -p
xcodebuild -version
echo "::endgroup::"
echo "::group::Available iOS runtimes"
xcrun simctl list runtimes
echo "::endgroup::"
echo "::group::Available device types"
xcrun simctl list devicetypes | grep -i 'iPhone\|iPad' | head -40
echo "::endgroup::"
echo "::group::Network config"
cat /etc/hosts
ifconfig lo0
echo "::endgroup::"

- name: Ensure ::1 localhost in /etc/hosts
run: |
if grep -qE '^::1[[:space:]]+localhost' /etc/hosts; then
echo "::1 localhost already present"
else
echo "::1 localhost" | sudo tee -a /etc/hosts
echo "Added ::1 localhost"
fi
echo "--- /etc/hosts after ---"
cat /etc/hosts

- name: npm ci
run: |
echo "::group::npm ci"
npm ci
echo "::endgroup::"

- name: npm run build
run: |
echo "::group::npm run build"
npm run build
echo "::endgroup::"

- name: Install ios-webkit-debug-proxy
run: |
echo "::group::brew install ios-webkit-debug-proxy"
brew install ios-webkit-debug-proxy
which ios_webkit_debug_proxy
ios_webkit_debug_proxy --help 2>&1 | head -40 || true
echo "::endgroup::"

- name: Boot iOS Simulator
uses: futureware-tech/simulator-action@v5
with:
# Per wiki/Devices-macos-15.md only iPhone 16/17 series ship pre-installed; iPhone 15 isn't.
model: 'iPhone 16'
os_version: '18.6'
wait_for_boot: true
boot_timeout_seconds: 300

- name: Simulator state after boot
run: |
echo "::group::Booted devices"
xcrun simctl list devices booted
echo "::endgroup::"
echo "::group::Simulator processes"
pgrep -lf Simulator || true
pgrep -lf launchd_sim || true
echo "::endgroup::"

- name: Locate simulator webinspectord socket
run: |
echo "::group::Locating com.apple.webinspectord_sim.socket"
# On modern macOS, ios_webkit_debug_proxy can no longer auto-discover the simulator;
# we have to point -s at the launchd-owned unix socket.
for i in $(seq 1 15); do
SOCK=$(lsof -aUc launchd_sim 2>/dev/null | awk '/com\.apple\.webinspectord_sim\.socket/{print $NF; exit}')
[[ -n "$SOCK" ]] && break
echo "attempt $i: socket not found yet"
sleep 1
done
if [[ -z "$SOCK" ]]; then
echo "Failed to locate webinspectord_sim.socket"
echo "--- launchd_sim file table ---"
lsof -aUc launchd_sim 2>/dev/null || true
exit 1
fi
echo "socket: $SOCK"
echo "SIM_WI_SOCKET=unix:$SOCK" >> $GITHUB_ENV
echo "::endgroup::"

- name: Start ios-webkit-debug-proxy
run: |
echo "::group::Starting proxy (SIM_WI_SOCKET=$SIM_WI_SOCKET)"
ios_webkit_debug_proxy -F -d -s "$SIM_WI_SOCKET" -c "null:9221,:9222-9322" > "$RUNNER_TEMP/iwdp.log" 2>&1 &
PID=$!
echo "IWDP_PID=$PID" >> $GITHUB_ENV
echo "proxy pid=$PID"
sleep 3
if ! kill -0 "$PID" 2>/dev/null; then
echo "Proxy died immediately. Log:"
cat "$RUNNER_TEMP/iwdp.log"
exit 1
fi
echo "::endgroup::"
echo "::group::Listening ports"
lsof -nP -iTCP -sTCP:LISTEN | grep -E "9221|9222|ios_webkit" || true
echo "::endgroup::"

- name: Run WebView tests
run: |
echo "::group::Test run (shard ${{ matrix.shard }}/4)"
npx playwright test --config tests/webview/playwright.config.ts --shard=${{ matrix.shard }}/4
echo "::endgroup::"

- name: Stop proxy
if: always()
run: |
[[ -n "$IWDP_PID" ]] && kill "$IWDP_PID" 2>/dev/null || true
# Simulator shutdown is owned by futureware-tech/simulator-action's post step.

- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: webview-simulator-logs-${{ matrix.shard }}
path: |
${{ github.workspace }}/test-results/**
if-no-files-found: ignore
1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
"ctest": "playwright test --config=tests/library/playwright.config.ts --project=chromium-*",
"ftest": "playwright test --config=tests/library/playwright.config.ts --project=firefox-*",
"wtest": "playwright test --config=tests/library/playwright.config.ts --project=webkit-*",
"wvtest": "playwright test --config=tests/webview/playwright.config.ts",
"atest": "playwright test --config=tests/android/playwright.config.ts",
"etest": "playwright test --config=tests/electron/playwright.config.ts",
"itest": "playwright test --config=tests/installation/playwright.config.ts",
Expand Down
5 changes: 3 additions & 2 deletions packages/injected/src/injectedScript.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1112,8 +1112,9 @@ export class InjectedScript {
return;

// Playwright only issues trusted events, so allow any custom events originating from
// the page or content scripts.
if (!event.isTrusted)
// the page or content scripts. The WebView backend cannot produce trusted events, so
// it marks synthetic events with __pwTrustedSynthetic to opt back into interception.
if (!event.isTrusted && !(event as any).__pwTrustedSynthetic)
return;

// Determine the event point. Note that Firefox does not always have window.TouchEvent.
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright-core/src/client/browserType.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -150,8 +150,8 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
}

async _connectOverCDP(endpointURL: string, params: api.ConnectOverCDPOptions = {}): Promise<Browser> {
if (this.name() !== 'chromium')
throw new Error('Connecting over CDP is only supported in Chromium.');
if (this.name() !== 'chromium' && this.name() !== 'webkit')
throw new Error('Connecting over CDP is only supported in Chromium and WebKit.');
const headers = params.headers ? headersObjectToArray(params.headers) : undefined;
const result = await this._channel.connectOverCDP({
endpointURL,
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright-core/src/server/webkit/DEPS.list
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
[*]
@isomorphic/**
@utils/**
../
../registry/
node_modules/jpeg-js
node_modules/pngjs

[webkit.ts]
./webview/wvBrowser.ts
9 changes: 8 additions & 1 deletion packages/playwright-core/src/server/webkit/webkit.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,11 +20,14 @@ import path from 'path';
import { wrapInASCIIBox } from '@utils/ascii';
import { spawnAsync } from '@utils/spawnAsync';
import { kBrowserCloseMessageId } from './wkConnection';
import { Browser } from '../browser';
import { BrowserType, kNoXServerRunningError } from '../browserType';
import { WKBrowser } from '../webkit/wkBrowser';
import { WKBrowser } from './wkBrowser';
import { connectOverRDP } from './webview/wvBrowser';

import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
import type { Progress } from '../progress';
import type { ConnectionTransport } from '../transport';
import type * as types from '../types';

Expand All@@ -37,6 +40,10 @@ export class WebKit extends BrowserType {
return WKBrowser.connect(this.attribution.playwright, transport, options);
}

override async connectOverCDP(progress: Progress, endpointURL: string, options: { slowMo?: number, headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean }): Promise<Browser> {
return connectOverRDP(progress, this, endpointURL, options);
}

override amendEnvironment(env: NodeJS.ProcessEnv, userDataDir: string, isPersistent: boolean, options: types.LaunchOptions): NodeJS.ProcessEnv {
return {
...env,
Expand Down
146 changes: 146 additions & 0 deletions packages/playwright-core/src/server/webkit/webview/dialogBridge.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { debugLogger } from '@utils/debugLogger';
import { createHttpServer } from '@utils/network';

import type { IncomingMessage, Server, ServerResponse } from 'http';

export type DialogRequest = {
type: 'alert' | 'confirm' | 'prompt';
message: string;
defaultValue: string;
};

export type DialogResult = {
accept: boolean;
promptText?: string;
};

type DialogHandler = (req: DialogRequest) => Promise<DialogResult>;

export class DialogBridge {
private readonly _server: Server;
private readonly _baseUrl: string;
private readonly _handlers = new Map<string, DialogHandler>();

static async start(): Promise<DialogBridge> {
const server = createHttpServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string')
throw new Error('DialogBridge: failed to bind HTTP server');
return new DialogBridge(server, `http://127.0.0.1:${address.port}`);
}

private constructor(server: Server, baseUrl: string) {
this._server = server;
this._baseUrl = baseUrl;
this._server.on('request', (req, res) => this._handleRequest(req, res));
}

endpointFor(pageId: string): string {
return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`;
}

registerTab(pageId: string, handler: DialogHandler): void {
this._handlers.set(pageId, handler);
}

unregisterTab(pageId: string): void {
this._handlers.delete(pageId);
}

async close(): Promise<void> {
this._handlers.clear();
await new Promise<void>(resolve => this._server.close(() => resolve()));
}

private _writeCorsHeaders(res: ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
}

private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
this._writeCorsHeaders(res);

if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}

const url = new URL(req.url || '/', this._baseUrl);
if (!(req.method === 'POST' && url.pathname === '/dialog')) {
res.statusCode = 404;
res.end();
return;
}

const tab = url.searchParams.get('tab') || '';
const handler = this._handlers.get(tab);
if (!handler) {
// Either the tab is gone or the page raced ahead of registerTab. Reply
// 404 so the page-side override silently falls through.
res.statusCode = 404;
res.end();
return;
}

let body = '';
req.setEncoding('utf8');
req.on('data', chunk => { body += chunk; });
req.on('end', async () => {
let parsed: DialogRequest;
try {
const json = JSON.parse(body);
if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt')
throw new Error(`Invalid dialog type: ${json.type}`);
parsed = {
type: json.type,
message: typeof json.message === 'string' ? json.message : '',
defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '',
};
} catch (e) {
debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`);
res.statusCode = 400;
res.end();
return;
}

try {
const result = await handler(parsed);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
accept: !!result.accept,
promptText: result.promptText,
}));
} catch (e) {
debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`);
res.statusCode = 500;
res.end();
}
});
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' chore: wk_webview experiment by pavelfeldman · Pull Request #41010 · microsoft/playwright · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .github/workflows/tests_webview_simulator.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
name: "tests WebView (iOS Simulator)"

on:
# pull_request trigger disabled to avoid CI churn during wk_wv iteration - restore before merge

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

env:
FORCE_COLOR: 1
ELECTRON_SKIP_BINARY_DOWNLOAD: 1

jobs:
test_webview_simulator:
name: "WebView on iOS Simulator (${{ matrix.shard }}/4)"
runs-on: macos-15
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Runner environment
run: |
echo "::group::OS / Xcode"
sw_vers
uname -a
xcode-select -p
xcodebuild -version
echo "::endgroup::"
echo "::group::Available iOS runtimes"
xcrun simctl list runtimes
echo "::endgroup::"
echo "::group::Available device types"
xcrun simctl list devicetypes | grep -i 'iPhone\|iPad' | head -40
echo "::endgroup::"
echo "::group::Network config"
cat /etc/hosts
ifconfig lo0
echo "::endgroup::"

- name: Ensure ::1 localhost in /etc/hosts
run: |
if grep -qE '^::1[[:space:]]+localhost' /etc/hosts; then
echo "::1 localhost already present"
else
echo "::1 localhost" | sudo tee -a /etc/hosts
echo "Added ::1 localhost"
fi
echo "--- /etc/hosts after ---"
cat /etc/hosts

- name: npm ci
run: |
echo "::group::npm ci"
npm ci
echo "::endgroup::"

- name: npm run build
run: |
echo "::group::npm run build"
npm run build
echo "::endgroup::"

- name: Install ios-webkit-debug-proxy
run: |
echo "::group::brew install ios-webkit-debug-proxy"
brew install ios-webkit-debug-proxy
which ios_webkit_debug_proxy
ios_webkit_debug_proxy --help 2>&1 | head -40 || true
echo "::endgroup::"

- name: Boot iOS Simulator
uses: futureware-tech/simulator-action@v5
with:
# Per wiki/Devices-macos-15.md only iPhone 16/17 series ship pre-installed; iPhone 15 isn't.
model: 'iPhone 16'
os_version: '18.6'
wait_for_boot: true
boot_timeout_seconds: 300

- name: Simulator state after boot
run: |
echo "::group::Booted devices"
xcrun simctl list devices booted
echo "::endgroup::"
echo "::group::Simulator processes"
pgrep -lf Simulator || true
pgrep -lf launchd_sim || true
echo "::endgroup::"

- name: Locate simulator webinspectord socket
run: |
echo "::group::Locating com.apple.webinspectord_sim.socket"
# On modern macOS, ios_webkit_debug_proxy can no longer auto-discover the simulator;
# we have to point -s at the launchd-owned unix socket.
for i in $(seq 1 15); do
SOCK=$(lsof -aUc launchd_sim 2>/dev/null | awk '/com\.apple\.webinspectord_sim\.socket/{print $NF; exit}')
[[ -n "$SOCK" ]] && break
echo "attempt $i: socket not found yet"
sleep 1
done
if [[ -z "$SOCK" ]]; then
echo "Failed to locate webinspectord_sim.socket"
echo "--- launchd_sim file table ---"
lsof -aUc launchd_sim 2>/dev/null || true
exit 1
fi
echo "socket: $SOCK"
echo "SIM_WI_SOCKET=unix:$SOCK" >> $GITHUB_ENV
echo "::endgroup::"

- name: Start ios-webkit-debug-proxy
run: |
echo "::group::Starting proxy (SIM_WI_SOCKET=$SIM_WI_SOCKET)"
ios_webkit_debug_proxy -F -d -s "$SIM_WI_SOCKET" -c "null:9221,:9222-9322" > "$RUNNER_TEMP/iwdp.log" 2>&1 &
PID=$!
echo "IWDP_PID=$PID" >> $GITHUB_ENV
echo "proxy pid=$PID"
sleep 3
if ! kill -0 "$PID" 2>/dev/null; then
echo "Proxy died immediately. Log:"
cat "$RUNNER_TEMP/iwdp.log"
exit 1
fi
echo "::endgroup::"
echo "::group::Listening ports"
lsof -nP -iTCP -sTCP:LISTEN | grep -E "9221|9222|ios_webkit" || true
echo "::endgroup::"

- name: Run WebView tests
run: |
echo "::group::Test run (shard ${{ matrix.shard }}/4)"
npx playwright test --config tests/webview/playwright.config.ts --shard=${{ matrix.shard }}/4
echo "::endgroup::"

- name: Stop proxy
if: always()
run: |
[[ -n "$IWDP_PID" ]] && kill "$IWDP_PID" 2>/dev/null || true
# Simulator shutdown is owned by futureware-tech/simulator-action's post step.

- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: webview-simulator-logs-${{ matrix.shard }}
path: |
${{ github.workspace }}/test-results/**
if-no-files-found: ignore
1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
"ctest": "playwright test --config=tests/library/playwright.config.ts --project=chromium-*",
"ftest": "playwright test --config=tests/library/playwright.config.ts --project=firefox-*",
"wtest": "playwright test --config=tests/library/playwright.config.ts --project=webkit-*",
"wvtest": "playwright test --config=tests/webview/playwright.config.ts",
"atest": "playwright test --config=tests/android/playwright.config.ts",
"etest": "playwright test --config=tests/electron/playwright.config.ts",
"itest": "playwright test --config=tests/installation/playwright.config.ts",
Expand Down
5 changes: 3 additions & 2 deletions packages/injected/src/injectedScript.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1112,8 +1112,9 @@ export class InjectedScript {
return;

// Playwright only issues trusted events, so allow any custom events originating from
// the page or content scripts.
if (!event.isTrusted)
// the page or content scripts. The WebView backend cannot produce trusted events, so
// it marks synthetic events with __pwTrustedSynthetic to opt back into interception.
if (!event.isTrusted && !(event as any).__pwTrustedSynthetic)
return;

// Determine the event point. Note that Firefox does not always have window.TouchEvent.
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright-core/src/client/browserType.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -150,8 +150,8 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
}

async _connectOverCDP(endpointURL: string, params: api.ConnectOverCDPOptions = {}): Promise<Browser> {
if (this.name() !== 'chromium')
throw new Error('Connecting over CDP is only supported in Chromium.');
if (this.name() !== 'chromium' && this.name() !== 'webkit')
throw new Error('Connecting over CDP is only supported in Chromium and WebKit.');
const headers = params.headers ? headersObjectToArray(params.headers) : undefined;
const result = await this._channel.connectOverCDP({
endpointURL,
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright-core/src/server/webkit/DEPS.list
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
[*]
@isomorphic/**
@utils/**
../
../registry/
node_modules/jpeg-js
node_modules/pngjs

[webkit.ts]
./webview/wvBrowser.ts
9 changes: 8 additions & 1 deletion packages/playwright-core/src/server/webkit/webkit.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,11 +20,14 @@ import path from 'path';
import { wrapInASCIIBox } from '@utils/ascii';
import { spawnAsync } from '@utils/spawnAsync';
import { kBrowserCloseMessageId } from './wkConnection';
import { Browser } from '../browser';
import { BrowserType, kNoXServerRunningError } from '../browserType';
import { WKBrowser } from '../webkit/wkBrowser';
import { WKBrowser } from './wkBrowser';
import { connectOverRDP } from './webview/wvBrowser';

import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
import type { Progress } from '../progress';
import type { ConnectionTransport } from '../transport';
import type * as types from '../types';

Expand All@@ -37,6 +40,10 @@ export class WebKit extends BrowserType {
return WKBrowser.connect(this.attribution.playwright, transport, options);
}

override async connectOverCDP(progress: Progress, endpointURL: string, options: { slowMo?: number, headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean }): Promise<Browser> {
return connectOverRDP(progress, this, endpointURL, options);
}

override amendEnvironment(env: NodeJS.ProcessEnv, userDataDir: string, isPersistent: boolean, options: types.LaunchOptions): NodeJS.ProcessEnv {
return {
...env,
Expand Down
146 changes: 146 additions & 0 deletions packages/playwright-core/src/server/webkit/webview/dialogBridge.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { debugLogger } from '@utils/debugLogger';
import { createHttpServer } from '@utils/network';

import type { IncomingMessage, Server, ServerResponse } from 'http';

export type DialogRequest = {
type: 'alert' | 'confirm' | 'prompt';
message: string;
defaultValue: string;
};

export type DialogResult = {
accept: boolean;
promptText?: string;
};

type DialogHandler = (req: DialogRequest) => Promise<DialogResult>;

export class DialogBridge {
private readonly _server: Server;
private readonly _baseUrl: string;
private readonly _handlers = new Map<string, DialogHandler>();

static async start(): Promise<DialogBridge> {
const server = createHttpServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string')
throw new Error('DialogBridge: failed to bind HTTP server');
return new DialogBridge(server, `http://127.0.0.1:${address.port}`);
}

private constructor(server: Server, baseUrl: string) {
this._server = server;
this._baseUrl = baseUrl;
this._server.on('request', (req, res) => this._handleRequest(req, res));
}

endpointFor(pageId: string): string {
return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`;
}

registerTab(pageId: string, handler: DialogHandler): void {
this._handlers.set(pageId, handler);
}

unregisterTab(pageId: string): void {
this._handlers.delete(pageId);
}

async close(): Promise<void> {
this._handlers.clear();
await new Promise<void>(resolve => this._server.close(() => resolve()));
}

private _writeCorsHeaders(res: ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
}

private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
this._writeCorsHeaders(res);

if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}

const url = new URL(req.url || '/', this._baseUrl);
if (!(req.method === 'POST' && url.pathname === '/dialog')) {
res.statusCode = 404;
res.end();
return;
}

const tab = url.searchParams.get('tab') || '';
const handler = this._handlers.get(tab);
if (!handler) {
// Either the tab is gone or the page raced ahead of registerTab. Reply
// 404 so the page-side override silently falls through.
res.statusCode = 404;
res.end();
return;
}

let body = '';
req.setEncoding('utf8');
req.on('data', chunk => { body += chunk; });
req.on('end', async () => {
let parsed: DialogRequest;
try {
const json = JSON.parse(body);
if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt')
throw new Error(`Invalid dialog type: ${json.type}`);
parsed = {
type: json.type,
message: typeof json.message === 'string' ? json.message : '',
defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '',
};
} catch (e) {
debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`);
res.statusCode = 400;
res.end();
return;
}

try {
const result = await handler(parsed);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
accept: !!result.accept,
promptText: result.promptText,
}));
} catch (e) {
debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`);
res.statusCode = 500;
res.end();
}
});
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' chore: wk_webview experiment by pavelfeldman · Pull Request #41010 · microsoft/playwright · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .github/workflows/tests_webview_simulator.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
name: "tests WebView (iOS Simulator)"

on:
# pull_request trigger disabled to avoid CI churn during wk_wv iteration - restore before merge

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

env:
FORCE_COLOR: 1
ELECTRON_SKIP_BINARY_DOWNLOAD: 1

jobs:
test_webview_simulator:
name: "WebView on iOS Simulator (${{ matrix.shard }}/4)"
runs-on: macos-15
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Runner environment
run: |
echo "::group::OS / Xcode"
sw_vers
uname -a
xcode-select -p
xcodebuild -version
echo "::endgroup::"
echo "::group::Available iOS runtimes"
xcrun simctl list runtimes
echo "::endgroup::"
echo "::group::Available device types"
xcrun simctl list devicetypes | grep -i 'iPhone\|iPad' | head -40
echo "::endgroup::"
echo "::group::Network config"
cat /etc/hosts
ifconfig lo0
echo "::endgroup::"

- name: Ensure ::1 localhost in /etc/hosts
run: |
if grep -qE '^::1[[:space:]]+localhost' /etc/hosts; then
echo "::1 localhost already present"
else
echo "::1 localhost" | sudo tee -a /etc/hosts
echo "Added ::1 localhost"
fi
echo "--- /etc/hosts after ---"
cat /etc/hosts

- name: npm ci
run: |
echo "::group::npm ci"
npm ci
echo "::endgroup::"

- name: npm run build
run: |
echo "::group::npm run build"
npm run build
echo "::endgroup::"

- name: Install ios-webkit-debug-proxy
run: |
echo "::group::brew install ios-webkit-debug-proxy"
brew install ios-webkit-debug-proxy
which ios_webkit_debug_proxy
ios_webkit_debug_proxy --help 2>&1 | head -40 || true
echo "::endgroup::"

- name: Boot iOS Simulator
uses: futureware-tech/simulator-action@v5
with:
# Per wiki/Devices-macos-15.md only iPhone 16/17 series ship pre-installed; iPhone 15 isn't.
model: 'iPhone 16'
os_version: '18.6'
wait_for_boot: true
boot_timeout_seconds: 300

- name: Simulator state after boot
run: |
echo "::group::Booted devices"
xcrun simctl list devices booted
echo "::endgroup::"
echo "::group::Simulator processes"
pgrep -lf Simulator || true
pgrep -lf launchd_sim || true
echo "::endgroup::"

- name: Locate simulator webinspectord socket
run: |
echo "::group::Locating com.apple.webinspectord_sim.socket"
# On modern macOS, ios_webkit_debug_proxy can no longer auto-discover the simulator;
# we have to point -s at the launchd-owned unix socket.
for i in $(seq 1 15); do
SOCK=$(lsof -aUc launchd_sim 2>/dev/null | awk '/com\.apple\.webinspectord_sim\.socket/{print $NF; exit}')
[[ -n "$SOCK" ]] && break
echo "attempt $i: socket not found yet"
sleep 1
done
if [[ -z "$SOCK" ]]; then
echo "Failed to locate webinspectord_sim.socket"
echo "--- launchd_sim file table ---"
lsof -aUc launchd_sim 2>/dev/null || true
exit 1
fi
echo "socket: $SOCK"
echo "SIM_WI_SOCKET=unix:$SOCK" >> $GITHUB_ENV
echo "::endgroup::"

- name: Start ios-webkit-debug-proxy
run: |
echo "::group::Starting proxy (SIM_WI_SOCKET=$SIM_WI_SOCKET)"
ios_webkit_debug_proxy -F -d -s "$SIM_WI_SOCKET" -c "null:9221,:9222-9322" > "$RUNNER_TEMP/iwdp.log" 2>&1 &
PID=$!
echo "IWDP_PID=$PID" >> $GITHUB_ENV
echo "proxy pid=$PID"
sleep 3
if ! kill -0 "$PID" 2>/dev/null; then
echo "Proxy died immediately. Log:"
cat "$RUNNER_TEMP/iwdp.log"
exit 1
fi
echo "::endgroup::"
echo "::group::Listening ports"
lsof -nP -iTCP -sTCP:LISTEN | grep -E "9221|9222|ios_webkit" || true
echo "::endgroup::"

- name: Run WebView tests
run: |
echo "::group::Test run (shard ${{ matrix.shard }}/4)"
npx playwright test --config tests/webview/playwright.config.ts --shard=${{ matrix.shard }}/4
echo "::endgroup::"

- name: Stop proxy
if: always()
run: |
[[ -n "$IWDP_PID" ]] && kill "$IWDP_PID" 2>/dev/null || true
# Simulator shutdown is owned by futureware-tech/simulator-action's post step.

- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: webview-simulator-logs-${{ matrix.shard }}
path: |
${{ github.workspace }}/test-results/**
if-no-files-found: ignore
1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
"ctest": "playwright test --config=tests/library/playwright.config.ts --project=chromium-*",
"ftest": "playwright test --config=tests/library/playwright.config.ts --project=firefox-*",
"wtest": "playwright test --config=tests/library/playwright.config.ts --project=webkit-*",
"wvtest": "playwright test --config=tests/webview/playwright.config.ts",
"atest": "playwright test --config=tests/android/playwright.config.ts",
"etest": "playwright test --config=tests/electron/playwright.config.ts",
"itest": "playwright test --config=tests/installation/playwright.config.ts",
Expand Down
5 changes: 3 additions & 2 deletions packages/injected/src/injectedScript.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1112,8 +1112,9 @@ export class InjectedScript {
return;

// Playwright only issues trusted events, so allow any custom events originating from
// the page or content scripts.
if (!event.isTrusted)
// the page or content scripts. The WebView backend cannot produce trusted events, so
// it marks synthetic events with __pwTrustedSynthetic to opt back into interception.
if (!event.isTrusted && !(event as any).__pwTrustedSynthetic)
return;

// Determine the event point. Note that Firefox does not always have window.TouchEvent.
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright-core/src/client/browserType.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -150,8 +150,8 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
}

async _connectOverCDP(endpointURL: string, params: api.ConnectOverCDPOptions = {}): Promise<Browser> {
if (this.name() !== 'chromium')
throw new Error('Connecting over CDP is only supported in Chromium.');
if (this.name() !== 'chromium' && this.name() !== 'webkit')
throw new Error('Connecting over CDP is only supported in Chromium and WebKit.');
const headers = params.headers ? headersObjectToArray(params.headers) : undefined;
const result = await this._channel.connectOverCDP({
endpointURL,
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright-core/src/server/webkit/DEPS.list
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
[*]
@isomorphic/**
@utils/**
../
../registry/
node_modules/jpeg-js
node_modules/pngjs

[webkit.ts]
./webview/wvBrowser.ts
9 changes: 8 additions & 1 deletion packages/playwright-core/src/server/webkit/webkit.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,11 +20,14 @@ import path from 'path';
import { wrapInASCIIBox } from '@utils/ascii';
import { spawnAsync } from '@utils/spawnAsync';
import { kBrowserCloseMessageId } from './wkConnection';
import { Browser } from '../browser';
import { BrowserType, kNoXServerRunningError } from '../browserType';
import { WKBrowser } from '../webkit/wkBrowser';
import { WKBrowser } from './wkBrowser';
import { connectOverRDP } from './webview/wvBrowser';

import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
import type { Progress } from '../progress';
import type { ConnectionTransport } from '../transport';
import type * as types from '../types';

Expand All@@ -37,6 +40,10 @@ export class WebKit extends BrowserType {
return WKBrowser.connect(this.attribution.playwright, transport, options);
}

override async connectOverCDP(progress: Progress, endpointURL: string, options: { slowMo?: number, headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean }): Promise<Browser> {
return connectOverRDP(progress, this, endpointURL, options);
}

override amendEnvironment(env: NodeJS.ProcessEnv, userDataDir: string, isPersistent: boolean, options: types.LaunchOptions): NodeJS.ProcessEnv {
return {
...env,
Expand Down
146 changes: 146 additions & 0 deletions packages/playwright-core/src/server/webkit/webview/dialogBridge.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { debugLogger } from '@utils/debugLogger';
import { createHttpServer } from '@utils/network';

import type { IncomingMessage, Server, ServerResponse } from 'http';

export type DialogRequest = {
type: 'alert' | 'confirm' | 'prompt';
message: string;
defaultValue: string;
};

export type DialogResult = {
accept: boolean;
promptText?: string;
};

type DialogHandler = (req: DialogRequest) => Promise<DialogResult>;

export class DialogBridge {
private readonly _server: Server;
private readonly _baseUrl: string;
private readonly _handlers = new Map<string, DialogHandler>();

static async start(): Promise<DialogBridge> {
const server = createHttpServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string')
throw new Error('DialogBridge: failed to bind HTTP server');
return new DialogBridge(server, `http://127.0.0.1:${address.port}`);
}

private constructor(server: Server, baseUrl: string) {
this._server = server;
this._baseUrl = baseUrl;
this._server.on('request', (req, res) => this._handleRequest(req, res));
}

endpointFor(pageId: string): string {
return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`;
}

registerTab(pageId: string, handler: DialogHandler): void {
this._handlers.set(pageId, handler);
}

unregisterTab(pageId: string): void {
this._handlers.delete(pageId);
}

async close(): Promise<void> {
this._handlers.clear();
await new Promise<void>(resolve => this._server.close(() => resolve()));
}

private _writeCorsHeaders(res: ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
}

private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
this._writeCorsHeaders(res);

if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}

const url = new URL(req.url || '/', this._baseUrl);
if (!(req.method === 'POST' && url.pathname === '/dialog')) {
res.statusCode = 404;
res.end();
return;
}

const tab = url.searchParams.get('tab') || '';
const handler = this._handlers.get(tab);
if (!handler) {
// Either the tab is gone or the page raced ahead of registerTab. Reply
// 404 so the page-side override silently falls through.
res.statusCode = 404;
res.end();
return;
}

let body = '';
req.setEncoding('utf8');
req.on('data', chunk => { body += chunk; });
req.on('end', async () => {
let parsed: DialogRequest;
try {
const json = JSON.parse(body);
if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt')
throw new Error(`Invalid dialog type: ${json.type}`);
parsed = {
type: json.type,
message: typeof json.message === 'string' ? json.message : '',
defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '',
};
} catch (e) {
debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`);
res.statusCode = 400;
res.end();
return;
}

try {
const result = await handler(parsed);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
accept: !!result.accept,
promptText: result.promptText,
}));
} catch (e) {
debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`);
res.statusCode = 500;
res.end();
}
});
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' chore: wk_webview experiment by pavelfeldman · Pull Request #41010 · microsoft/playwright · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .github/workflows/tests_webview_simulator.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
name: "tests WebView (iOS Simulator)"

on:
# pull_request trigger disabled to avoid CI churn during wk_wv iteration - restore before merge

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

env:
FORCE_COLOR: 1
ELECTRON_SKIP_BINARY_DOWNLOAD: 1

jobs:
test_webview_simulator:
name: "WebView on iOS Simulator (${{ matrix.shard }}/4)"
runs-on: macos-15
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Runner environment
run: |
echo "::group::OS / Xcode"
sw_vers
uname -a
xcode-select -p
xcodebuild -version
echo "::endgroup::"
echo "::group::Available iOS runtimes"
xcrun simctl list runtimes
echo "::endgroup::"
echo "::group::Available device types"
xcrun simctl list devicetypes | grep -i 'iPhone\|iPad' | head -40
echo "::endgroup::"
echo "::group::Network config"
cat /etc/hosts
ifconfig lo0
echo "::endgroup::"

- name: Ensure ::1 localhost in /etc/hosts
run: |
if grep -qE '^::1[[:space:]]+localhost' /etc/hosts; then
echo "::1 localhost already present"
else
echo "::1 localhost" | sudo tee -a /etc/hosts
echo "Added ::1 localhost"
fi
echo "--- /etc/hosts after ---"
cat /etc/hosts

- name: npm ci
run: |
echo "::group::npm ci"
npm ci
echo "::endgroup::"

- name: npm run build
run: |
echo "::group::npm run build"
npm run build
echo "::endgroup::"

- name: Install ios-webkit-debug-proxy
run: |
echo "::group::brew install ios-webkit-debug-proxy"
brew install ios-webkit-debug-proxy
which ios_webkit_debug_proxy
ios_webkit_debug_proxy --help 2>&1 | head -40 || true
echo "::endgroup::"

- name: Boot iOS Simulator
uses: futureware-tech/simulator-action@v5
with:
# Per wiki/Devices-macos-15.md only iPhone 16/17 series ship pre-installed; iPhone 15 isn't.
model: 'iPhone 16'
os_version: '18.6'
wait_for_boot: true
boot_timeout_seconds: 300

- name: Simulator state after boot
run: |
echo "::group::Booted devices"
xcrun simctl list devices booted
echo "::endgroup::"
echo "::group::Simulator processes"
pgrep -lf Simulator || true
pgrep -lf launchd_sim || true
echo "::endgroup::"

- name: Locate simulator webinspectord socket
run: |
echo "::group::Locating com.apple.webinspectord_sim.socket"
# On modern macOS, ios_webkit_debug_proxy can no longer auto-discover the simulator;
# we have to point -s at the launchd-owned unix socket.
for i in $(seq 1 15); do
SOCK=$(lsof -aUc launchd_sim 2>/dev/null | awk '/com\.apple\.webinspectord_sim\.socket/{print $NF; exit}')
[[ -n "$SOCK" ]] && break
echo "attempt $i: socket not found yet"
sleep 1
done
if [[ -z "$SOCK" ]]; then
echo "Failed to locate webinspectord_sim.socket"
echo "--- launchd_sim file table ---"
lsof -aUc launchd_sim 2>/dev/null || true
exit 1
fi
echo "socket: $SOCK"
echo "SIM_WI_SOCKET=unix:$SOCK" >> $GITHUB_ENV
echo "::endgroup::"

- name: Start ios-webkit-debug-proxy
run: |
echo "::group::Starting proxy (SIM_WI_SOCKET=$SIM_WI_SOCKET)"
ios_webkit_debug_proxy -F -d -s "$SIM_WI_SOCKET" -c "null:9221,:9222-9322" > "$RUNNER_TEMP/iwdp.log" 2>&1 &
PID=$!
echo "IWDP_PID=$PID" >> $GITHUB_ENV
echo "proxy pid=$PID"
sleep 3
if ! kill -0 "$PID" 2>/dev/null; then
echo "Proxy died immediately. Log:"
cat "$RUNNER_TEMP/iwdp.log"
exit 1
fi
echo "::endgroup::"
echo "::group::Listening ports"
lsof -nP -iTCP -sTCP:LISTEN | grep -E "9221|9222|ios_webkit" || true
echo "::endgroup::"

- name: Run WebView tests
run: |
echo "::group::Test run (shard ${{ matrix.shard }}/4)"
npx playwright test --config tests/webview/playwright.config.ts --shard=${{ matrix.shard }}/4
echo "::endgroup::"

- name: Stop proxy
if: always()
run: |
[[ -n "$IWDP_PID" ]] && kill "$IWDP_PID" 2>/dev/null || true
# Simulator shutdown is owned by futureware-tech/simulator-action's post step.

- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: webview-simulator-logs-${{ matrix.shard }}
path: |
${{ github.workspace }}/test-results/**
if-no-files-found: ignore
1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
"ctest": "playwright test --config=tests/library/playwright.config.ts --project=chromium-*",
"ftest": "playwright test --config=tests/library/playwright.config.ts --project=firefox-*",
"wtest": "playwright test --config=tests/library/playwright.config.ts --project=webkit-*",
"wvtest": "playwright test --config=tests/webview/playwright.config.ts",
"atest": "playwright test --config=tests/android/playwright.config.ts",
"etest": "playwright test --config=tests/electron/playwright.config.ts",
"itest": "playwright test --config=tests/installation/playwright.config.ts",
Expand Down
5 changes: 3 additions & 2 deletions packages/injected/src/injectedScript.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1112,8 +1112,9 @@ export class InjectedScript {
return;

// Playwright only issues trusted events, so allow any custom events originating from
// the page or content scripts.
if (!event.isTrusted)
// the page or content scripts. The WebView backend cannot produce trusted events, so
// it marks synthetic events with __pwTrustedSynthetic to opt back into interception.
if (!event.isTrusted && !(event as any).__pwTrustedSynthetic)
return;

// Determine the event point. Note that Firefox does not always have window.TouchEvent.
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright-core/src/client/browserType.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -150,8 +150,8 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
}

async _connectOverCDP(endpointURL: string, params: api.ConnectOverCDPOptions = {}): Promise<Browser> {
if (this.name() !== 'chromium')
throw new Error('Connecting over CDP is only supported in Chromium.');
if (this.name() !== 'chromium' && this.name() !== 'webkit')
throw new Error('Connecting over CDP is only supported in Chromium and WebKit.');
const headers = params.headers ? headersObjectToArray(params.headers) : undefined;
const result = await this._channel.connectOverCDP({
endpointURL,
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright-core/src/server/webkit/DEPS.list
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
[*]
@isomorphic/**
@utils/**
../
../registry/
node_modules/jpeg-js
node_modules/pngjs

[webkit.ts]
./webview/wvBrowser.ts
9 changes: 8 additions & 1 deletion packages/playwright-core/src/server/webkit/webkit.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,11 +20,14 @@ import path from 'path';
import { wrapInASCIIBox } from '@utils/ascii';
import { spawnAsync } from '@utils/spawnAsync';
import { kBrowserCloseMessageId } from './wkConnection';
import { Browser } from '../browser';
import { BrowserType, kNoXServerRunningError } from '../browserType';
import { WKBrowser } from '../webkit/wkBrowser';
import { WKBrowser } from './wkBrowser';
import { connectOverRDP } from './webview/wvBrowser';

import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
import type { Progress } from '../progress';
import type { ConnectionTransport } from '../transport';
import type * as types from '../types';

Expand All@@ -37,6 +40,10 @@ export class WebKit extends BrowserType {
return WKBrowser.connect(this.attribution.playwright, transport, options);
}

override async connectOverCDP(progress: Progress, endpointURL: string, options: { slowMo?: number, headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean }): Promise<Browser> {
return connectOverRDP(progress, this, endpointURL, options);
}

override amendEnvironment(env: NodeJS.ProcessEnv, userDataDir: string, isPersistent: boolean, options: types.LaunchOptions): NodeJS.ProcessEnv {
return {
...env,
Expand Down
146 changes: 146 additions & 0 deletions packages/playwright-core/src/server/webkit/webview/dialogBridge.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { debugLogger } from '@utils/debugLogger';
import { createHttpServer } from '@utils/network';

import type { IncomingMessage, Server, ServerResponse } from 'http';

export type DialogRequest = {
type: 'alert' | 'confirm' | 'prompt';
message: string;
defaultValue: string;
};

export type DialogResult = {
accept: boolean;
promptText?: string;
};

type DialogHandler = (req: DialogRequest) => Promise<DialogResult>;

export class DialogBridge {
private readonly _server: Server;
private readonly _baseUrl: string;
private readonly _handlers = new Map<string, DialogHandler>();

static async start(): Promise<DialogBridge> {
const server = createHttpServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string')
throw new Error('DialogBridge: failed to bind HTTP server');
return new DialogBridge(server, `http://127.0.0.1:${address.port}`);
}

private constructor(server: Server, baseUrl: string) {
this._server = server;
this._baseUrl = baseUrl;
this._server.on('request', (req, res) => this._handleRequest(req, res));
}

endpointFor(pageId: string): string {
return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`;
}

registerTab(pageId: string, handler: DialogHandler): void {
this._handlers.set(pageId, handler);
}

unregisterTab(pageId: string): void {
this._handlers.delete(pageId);
}

async close(): Promise<void> {
this._handlers.clear();
await new Promise<void>(resolve => this._server.close(() => resolve()));
}

private _writeCorsHeaders(res: ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
}

private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
this._writeCorsHeaders(res);

if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}

const url = new URL(req.url || '/', this._baseUrl);
if (!(req.method === 'POST' && url.pathname === '/dialog')) {
res.statusCode = 404;
res.end();
return;
}

const tab = url.searchParams.get('tab') || '';
const handler = this._handlers.get(tab);
if (!handler) {
// Either the tab is gone or the page raced ahead of registerTab. Reply
// 404 so the page-side override silently falls through.
res.statusCode = 404;
res.end();
return;
}

let body = '';
req.setEncoding('utf8');
req.on('data', chunk => { body += chunk; });
req.on('end', async () => {
let parsed: DialogRequest;
try {
const json = JSON.parse(body);
if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt')
throw new Error(`Invalid dialog type: ${json.type}`);
parsed = {
type: json.type,
message: typeof json.message === 'string' ? json.message : '',
defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '',
};
} catch (e) {
debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`);
res.statusCode = 400;
res.end();
return;
}

try {
const result = await handler(parsed);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
accept: !!result.accept,
promptText: result.promptText,
}));
} catch (e) {
debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`);
res.statusCode = 500;
res.end();
}
});
}
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); chore: wk_webview experiment by pavelfeldman · Pull Request #41010 · microsoft/playwright · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions .github/workflows/tests_webview_simulator.yml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,156 @@
name: "tests WebView (iOS Simulator)"

on:
# pull_request trigger disabled to avoid CI churn during wk_wv iteration - restore before merge

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
cancel-in-progress: true

env:
FORCE_COLOR: 1
ELECTRON_SKIP_BINARY_DOWNLOAD: 1

jobs:
test_webview_simulator:
name: "WebView on iOS Simulator (${{ matrix.shard }}/4)"
runs-on: macos-15
timeout-minutes: 60
strategy:
fail-fast: false
matrix:
shard: [1, 2, 3, 4]
steps:
- uses: actions/checkout@v6
- uses: actions/setup-node@v4
with:
node-version: 20

- name: Runner environment
run: |
echo "::group::OS / Xcode"
sw_vers
uname -a
xcode-select -p
xcodebuild -version
echo "::endgroup::"
echo "::group::Available iOS runtimes"
xcrun simctl list runtimes
echo "::endgroup::"
echo "::group::Available device types"
xcrun simctl list devicetypes | grep -i 'iPhone\|iPad' | head -40
echo "::endgroup::"
echo "::group::Network config"
cat /etc/hosts
ifconfig lo0
echo "::endgroup::"

- name: Ensure ::1 localhost in /etc/hosts
run: |
if grep -qE '^::1[[:space:]]+localhost' /etc/hosts; then
echo "::1 localhost already present"
else
echo "::1 localhost" | sudo tee -a /etc/hosts
echo "Added ::1 localhost"
fi
echo "--- /etc/hosts after ---"
cat /etc/hosts

- name: npm ci
run: |
echo "::group::npm ci"
npm ci
echo "::endgroup::"

- name: npm run build
run: |
echo "::group::npm run build"
npm run build
echo "::endgroup::"

- name: Install ios-webkit-debug-proxy
run: |
echo "::group::brew install ios-webkit-debug-proxy"
brew install ios-webkit-debug-proxy
which ios_webkit_debug_proxy
ios_webkit_debug_proxy --help 2>&1 | head -40 || true
echo "::endgroup::"

- name: Boot iOS Simulator
uses: futureware-tech/simulator-action@v5
with:
# Per wiki/Devices-macos-15.md only iPhone 16/17 series ship pre-installed; iPhone 15 isn't.
model: 'iPhone 16'
os_version: '18.6'
wait_for_boot: true
boot_timeout_seconds: 300

- name: Simulator state after boot
run: |
echo "::group::Booted devices"
xcrun simctl list devices booted
echo "::endgroup::"
echo "::group::Simulator processes"
pgrep -lf Simulator || true
pgrep -lf launchd_sim || true
echo "::endgroup::"

- name: Locate simulator webinspectord socket
run: |
echo "::group::Locating com.apple.webinspectord_sim.socket"
# On modern macOS, ios_webkit_debug_proxy can no longer auto-discover the simulator;
# we have to point -s at the launchd-owned unix socket.
for i in $(seq 1 15); do
SOCK=$(lsof -aUc launchd_sim 2>/dev/null | awk '/com\.apple\.webinspectord_sim\.socket/{print $NF; exit}')
[[ -n "$SOCK" ]] && break
echo "attempt $i: socket not found yet"
sleep 1
done
if [[ -z "$SOCK" ]]; then
echo "Failed to locate webinspectord_sim.socket"
echo "--- launchd_sim file table ---"
lsof -aUc launchd_sim 2>/dev/null || true
exit 1
fi
echo "socket: $SOCK"
echo "SIM_WI_SOCKET=unix:$SOCK" >> $GITHUB_ENV
echo "::endgroup::"

- name: Start ios-webkit-debug-proxy
run: |
echo "::group::Starting proxy (SIM_WI_SOCKET=$SIM_WI_SOCKET)"
ios_webkit_debug_proxy -F -d -s "$SIM_WI_SOCKET" -c "null:9221,:9222-9322" > "$RUNNER_TEMP/iwdp.log" 2>&1 &
PID=$!
echo "IWDP_PID=$PID" >> $GITHUB_ENV
echo "proxy pid=$PID"
sleep 3
if ! kill -0 "$PID" 2>/dev/null; then
echo "Proxy died immediately. Log:"
cat "$RUNNER_TEMP/iwdp.log"
exit 1
fi
echo "::endgroup::"
echo "::group::Listening ports"
lsof -nP -iTCP -sTCP:LISTEN | grep -E "9221|9222|ios_webkit" || true
echo "::endgroup::"

- name: Run WebView tests
run: |
echo "::group::Test run (shard ${{ matrix.shard }}/4)"
npx playwright test --config tests/webview/playwright.config.ts --shard=${{ matrix.shard }}/4
echo "::endgroup::"

- name: Stop proxy
if: always()
run: |
[[ -n "$IWDP_PID" ]] && kill "$IWDP_PID" 2>/dev/null || true
# Simulator shutdown is owned by futureware-tech/simulator-action's post step.

- name: Upload artifacts
if: always()
uses: actions/upload-artifact@v4
with:
name: webview-simulator-logs-${{ matrix.shard }}
path: |
${{ github.workspace }}/test-results/**
if-no-files-found: ignore
1 change: 1 addition & 0 deletions package.json
Original file line numberDiff line numberDiff line change
Expand Up@@ -19,6 +19,7 @@
"ctest": "playwright test --config=tests/library/playwright.config.ts --project=chromium-*",
"ftest": "playwright test --config=tests/library/playwright.config.ts --project=firefox-*",
"wtest": "playwright test --config=tests/library/playwright.config.ts --project=webkit-*",
"wvtest": "playwright test --config=tests/webview/playwright.config.ts",
"atest": "playwright test --config=tests/android/playwright.config.ts",
"etest": "playwright test --config=tests/electron/playwright.config.ts",
"itest": "playwright test --config=tests/installation/playwright.config.ts",
Expand Down
5 changes: 3 additions & 2 deletions packages/injected/src/injectedScript.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -1112,8 +1112,9 @@ export class InjectedScript {
return;

// Playwright only issues trusted events, so allow any custom events originating from
// the page or content scripts.
if (!event.isTrusted)
// the page or content scripts. The WebView backend cannot produce trusted events, so
// it marks synthetic events with __pwTrustedSynthetic to opt back into interception.
if (!event.isTrusted && !(event as any).__pwTrustedSynthetic)
return;

// Determine the event point. Note that Firefox does not always have window.TouchEvent.
Expand Down
4 changes: 2 additions & 2 deletions packages/playwright-core/src/client/browserType.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -150,8 +150,8 @@ export class BrowserType extends ChannelOwner<channels.BrowserTypeChannel> imple
}

async _connectOverCDP(endpointURL: string, params: api.ConnectOverCDPOptions = {}): Promise<Browser> {
if (this.name() !== 'chromium')
throw new Error('Connecting over CDP is only supported in Chromium.');
if (this.name() !== 'chromium' && this.name() !== 'webkit')
throw new Error('Connecting over CDP is only supported in Chromium and WebKit.');
const headers = params.headers ? headersObjectToArray(params.headers) : undefined;
const result = await this._channel.connectOverCDP({
endpointURL,
Expand Down
10 changes: 10 additions & 0 deletions packages/playwright-core/src/server/webkit/DEPS.list
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
[*]
@isomorphic/**
@utils/**
../
../registry/
node_modules/jpeg-js
node_modules/pngjs

[webkit.ts]
./webview/wvBrowser.ts
9 changes: 8 additions & 1 deletion packages/playwright-core/src/server/webkit/webkit.ts
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,11 +20,14 @@ import path from 'path';
import { wrapInASCIIBox } from '@utils/ascii';
import { spawnAsync } from '@utils/spawnAsync';
import { kBrowserCloseMessageId } from './wkConnection';
import { Browser } from '../browser';
import { BrowserType, kNoXServerRunningError } from '../browserType';
import { WKBrowser } from '../webkit/wkBrowser';
import { WKBrowser } from './wkBrowser';
import { connectOverRDP } from './webview/wvBrowser';

import type { BrowserOptions } from '../browser';
import type { SdkObject } from '../instrumentation';
import type { Progress } from '../progress';
import type { ConnectionTransport } from '../transport';
import type * as types from '../types';

Expand All@@ -37,6 +40,10 @@ export class WebKit extends BrowserType {
return WKBrowser.connect(this.attribution.playwright, transport, options);
}

override async connectOverCDP(progress: Progress, endpointURL: string, options: { slowMo?: number, headers?: types.HeadersArray, isLocal?: boolean, noDefaults?: boolean }): Promise<Browser> {
return connectOverRDP(progress, this, endpointURL, options);
}

override amendEnvironment(env: NodeJS.ProcessEnv, userDataDir: string, isPersistent: boolean, options: types.LaunchOptions): NodeJS.ProcessEnv {
return {
...env,
Expand Down
146 changes: 146 additions & 0 deletions packages/playwright-core/src/server/webkit/webview/dialogBridge.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { debugLogger } from '@utils/debugLogger';
import { createHttpServer } from '@utils/network';

import type { IncomingMessage, Server, ServerResponse } from 'http';

export type DialogRequest = {
type: 'alert' | 'confirm' | 'prompt';
message: string;
defaultValue: string;
};

export type DialogResult = {
accept: boolean;
promptText?: string;
};

type DialogHandler = (req: DialogRequest) => Promise<DialogResult>;

export class DialogBridge {
private readonly _server: Server;
private readonly _baseUrl: string;
private readonly _handlers = new Map<string, DialogHandler>();

static async start(): Promise<DialogBridge> {
const server = createHttpServer();
await new Promise<void>((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
server.removeListener('error', reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === 'string')
throw new Error('DialogBridge: failed to bind HTTP server');
return new DialogBridge(server, `http://127.0.0.1:${address.port}`);
}

private constructor(server: Server, baseUrl: string) {
this._server = server;
this._baseUrl = baseUrl;
this._server.on('request', (req, res) => this._handleRequest(req, res));
}

endpointFor(pageId: string): string {
return `${this._baseUrl}/dialog?tab=${encodeURIComponent(pageId)}`;
}

registerTab(pageId: string, handler: DialogHandler): void {
this._handlers.set(pageId, handler);
}

unregisterTab(pageId: string): void {
this._handlers.delete(pageId);
}

async close(): Promise<void> {
this._handlers.clear();
await new Promise<void>(resolve => this._server.close(() => resolve()));
}

private _writeCorsHeaders(res: ServerResponse): void {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'content-type');
}

private async _handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
this._writeCorsHeaders(res);

if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}

const url = new URL(req.url || '/', this._baseUrl);
if (!(req.method === 'POST' && url.pathname === '/dialog')) {
res.statusCode = 404;
res.end();
return;
}

const tab = url.searchParams.get('tab') || '';
const handler = this._handlers.get(tab);
if (!handler) {
// Either the tab is gone or the page raced ahead of registerTab. Reply
// 404 so the page-side override silently falls through.
res.statusCode = 404;
res.end();
return;
}

let body = '';
req.setEncoding('utf8');
req.on('data', chunk => { body += chunk; });
req.on('end', async () => {
let parsed: DialogRequest;
try {
const json = JSON.parse(body);
if (json.type !== 'alert' && json.type !== 'confirm' && json.type !== 'prompt')
throw new Error(`Invalid dialog type: ${json.type}`);
parsed = {
type: json.type,
message: typeof json.message === 'string' ? json.message : '',
defaultValue: typeof json.defaultValue === 'string' ? json.defaultValue : '',
};
} catch (e) {
debugLogger.log('error', `DialogBridge: bad request body: ${(e as Error).message}`);
res.statusCode = 400;
res.end();
return;
}

try {
const result = await handler(parsed);
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({
accept: !!result.accept,
promptText: result.promptText,
}));
} catch (e) {
debugLogger.log('error', `DialogBridge: handler error: ${(e as Error).message}`);
res.statusCode = 500;
res.end();
}
});
}
}
Loading
Loading