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
32 changes: 27 additions & 5 deletions .azure-pipelines/publish-docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ extends:

- task: UseNode@1
inputs:
version: '22.x'
version: '26.x'
displayName: "Install Node.js"

# Relocate the Docker data-root to the large /mnt volume: this job builds
Expand All @@ -67,13 +67,23 @@ extends:
echo '{ "data-root": "/mnt/docker" }' | sudo tee /etc/docker/daemon.json
sudo service docker start

# Register QEMU/binfmt handlers so `docker build --platform linux/arm64`
# works on the amd64 host. Equivalent to docker/setup-qemu-action@v4.
- task: Bash@3
displayName: "Set up QEMU for arm64 builds"
displayName: "setup .npmrc"
inputs:
targetType: "inline"
script: docker run --privileged --rm tonistiigi/binfmt --install arm64
script: |
echo "registry=https://devdiv.pkgs.visualstudio.com/DevDiv/_packaging/DevDiv_PublicPackages/npm/registry/" >> .npmrc
echo "registry=https://devdiv.pkgs.visualstudio.com/DevDiv/_packaging/DevDiv_PublicPackages/npm/registry/" >> tests/playwright-test/stable-test-runner/.npmrc

- task: npmAuthenticate@0
displayName: "authenticate the private npm registry"
inputs:
workingFile: .npmrc

- task: npmAuthenticate@0
displayName: "authenticate the private npm registry for stable-test-runner"
inputs:
workingFile: tests/playwright-test/stable-test-runner/.npmrc

- script: npm ci
displayName: "npm ci"
Expand All @@ -89,8 +99,20 @@ extends:
scriptLocation: "inlineScript"
inlineScript: "az acr login --name playwright"

- task: Bash@3
displayName: "Register QEMU (binfmt) for arm64 cross-build"
inputs:
targetType: "inline"
script: "docker run --rm --privileged ${ACR_CACHE_PREFIX}tonistiigi/binfmt --install arm64"
env:
ACR_CACHE_PREFIX: "playwright.azurecr.io/cached/"

- task: Bash@3
displayName: "Build & publish Docker images"
inputs:
targetType: "inline"
script: "./utils/docker/publish_docker.sh ${{ parameters.releaseChannel }}"
env:
ACR_CACHE_PREFIX: "playwright.azurecr.io/cached/"
UBUNTU_MIRROR_PREFIX: "azure."
NPMRC_SECRET: "$(Build.SourcesDirectory)/.npmrc"
37 changes: 0 additions & 37 deletions .github/workflows/publish_release_docker.yml

This file was deleted.

2 changes: 2 additions & 0 deletions .github/workflows/tests_bidi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ jobs:
- run: npx playwright install --with-deps chromium
- if: matrix.channel == 'moz-firefox-nightly'
run: |
sudo apt-get update
sudo apt-get install -y libavcodec60
echo "BIDI_FFPATH=$(npx -y @puppeteer/browsers install firefox@nightly | tail -n1 | sed 's/^[^ ]* *//')" >> "$GITHUB_ENV"
- name: Run tests
run: xvfb-run --auto-servernum --server-args="-screen 0 1280x960x24" -- npm run biditest -- --retries=${{ matrix.isPullRequest && 2 || 0 }} --project=${{ matrix.channel }}*
Expand Down
74 changes: 74 additions & 0 deletions packages/injected/src/bidiInsertText.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
/**
* 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 type { InjectedScript } from './injectedScript';

function bidiInsertText(window: Window, text: string): Element | undefined {
let element = window.document.activeElement;
while (element?.shadowRoot)
element = element.shadowRoot.activeElement;
if (!element)
return;
const elementType = element.nodeName.toLocaleLowerCase();
if (elementType === 'iframe' || elementType === 'frame') {
// The focused element lives inside a nested frame. Hand the frame element
// back to the caller so it can recurse into that frame.
return element;
} else if (elementType === 'input' || elementType === 'textarea') {
const inputElement = element as HTMLInputElement | HTMLTextAreaElement;
const start = inputElement.selectionStart;
if (start === null) {
inputElement.value += text;
} else {
let value = inputElement.value;
value = value.substring(0, start) + text + value.substring(inputElement.selectionEnd!);
inputElement.value = value;
const caretPosition = start + text.length;
inputElement.setSelectionRange(caretPosition, caretPosition);
}
inputElement.dispatchEvent(new InputEvent('input', { data: text, bubbles: true, composed: true }));
} else if (element instanceof HTMLElement && element.isContentEditable) {
const selection = window.getSelection()!;
let range;
if (selection.rangeCount)
range = selection.getRangeAt(0);
if (!range || !element.contains(range.commonAncestorContainer)) {
range = window.document.createRange();
range.selectNodeContents(element);
range.collapse(true);
}
range.deleteContents();
const lines = text.split('\n');
for (let i = lines.length - 1; i >= 0; i--) {
range.insertNode(window.document.createTextNode(lines[i]));
if (i > 0)
range.insertNode(window.document.createElement('br'));
}
range.collapse();
selection.removeAllRanges();
selection.addRange(range);
element.dispatchEvent(new InputEvent('input', { data: text, bubbles: true, composed: true }));
}
}

export class BidiInsertTextInstaller {
constructor(injectedScript: InjectedScript) {
const window = injectedScript.window;
(window as any).__pw_bidiInsertText = (text: string) => bidiInsertText(window, text);
}
}

export default BidiInsertTextInstaller;
1 change: 1 addition & 0 deletions packages/playwright-core/src/server/bidi/DEPS.list
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
@utils/**
@isomorphic/**
../
../../generated/
./third_party/

[bidiOverCdp.ts]
Expand Down
2 changes: 2 additions & 0 deletions packages/playwright-core/src/server/bidi/bidiBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { bidiBytesValueToString } from './bidiNetworkManager';
import { BidiPage, kPlaywrightBindingChannel } from './bidiPage';
import { PageBinding } from '../page';
import * as bidi from './third_party/bidiProtocol';
import * as rawBidiInsertTextSource from '../../generated/bidiInsertTextSource';

import type { RegisteredListener } from '@utils/eventsHelper';
import type { BrowserOptions } from '../browser';
Expand Down Expand Up @@ -226,6 +227,7 @@ export class BidiBrowserContext extends BrowserContext {
const promises: Promise<any>[] = [
super.initialize(),
];
promises.push(this.extendInjectedScript(rawBidiInsertTextSource.source));
const downloadBehavior: bidi.Browser.DownloadBehavior = this._options.acceptDownloads === 'accept' ?
{ type: 'allowed', destinationFolder: this._browser.options.downloadsPath } :
{ type: 'denied' };
Expand Down
39 changes: 24 additions & 15 deletions packages/playwright-core/src/server/bidi/bidiInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,19 @@ import { resolveSmartModifierString } from '../input';
import { getBidiKeyValue } from './third_party/bidiKeyboard';
import * as bidi from './third_party/bidiProtocol';

import type { Frame } from '../frames';
import type * as input from '../input';
import type * as types from '../types';
import type { BidiSession } from './bidiConnection';
import type { BidiPage } from './bidiPage';
import type { Progress } from '../progress';
import type { FrameExecutionContext } from '../dom';

export class RawKeyboardImpl implements input.RawKeyboard {
private _session: BidiSession;
private _page: BidiPage;

constructor(session: BidiSession) {
this._session = session;
}

setSession(session: BidiSession) {
this._session = session;
constructor(page: BidiPage) {
this._page = page;
}

async keydown(progress: Progress, modifiers: Set<types.KeyboardModifier>, keyName: string, description: input.KeyDescription, autoRepeat: boolean): Promise<void> {
Expand All @@ -49,18 +48,28 @@ export class RawKeyboardImpl implements input.RawKeyboard {
}

async sendText(progress: Progress, text: string): Promise<void> {
const actions: bidi.Input.KeySourceAction[] = [];
for (const char of text) {
const value = getBidiKeyValue(char);
actions.push({ type: 'keyDown', value });
actions.push({ type: 'keyUp', value });
let frame: Frame | null = this._page._page.mainFrame();
while (frame) {
const context: FrameExecutionContext = await progress.race(frame.mainContext());
const handle = await progress.race(context.evaluateHandle((text: string) => (window as any).__pw_bidiInsertText(text), text));
// insertText returns the focused frame element when the focus lives inside a nested frame,
// otherwise the text was inserted (if possible) and we are done.
const element = handle.asElement();
if (!element) {
handle.dispose();
return;
}
try {
frame = await progress.race(element.contentFrame(progress));
} finally {
element.dispose();
}
}
await this._performActions(progress, actions);
}

private async _performActions(progress: Progress, actions: bidi.Input.KeySourceAction[]) {
await progress.race(this._session.send('input.performActions', {
context: this._session.sessionId,
await progress.race(this._page._session.send('input.performActions', {
context: this._page._session.sessionId,
actions: [
{
type: 'key',
Expand Down
2 changes: 1 addition & 1 deletion packages/playwright-core/src/server/bidi/bidiPage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export class BidiPage implements PageDelegate {
constructor(browserContext: BidiBrowserContext, bidiSession: BidiSession, opener: BidiPage | null) {
this._session = bidiSession;
this._opener = opener;
this.rawKeyboard = new RawKeyboardImpl(bidiSession);
this.rawKeyboard = new RawKeyboardImpl(this);
this.rawMouse = new RawMouseImpl(bidiSession);
this.rawTouchscreen = new RawTouchscreenImpl(bidiSession);
this._contextIdToContext = new Map();
Expand Down
2 changes: 1 addition & 1 deletion packages/playwright-core/src/server/chromium/crBrowser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ export class CRBrowserContext extends BrowserContext<CREventsMap> {
}

override async doCreateNewPage(): Promise<Page> {
const { targetId } = await this._browser._session.send('Target.createTarget', { url: 'about:blank', browserContextId: this._browserContextId, background: false, focus: false });
const { targetId } = await this._browser._session.send('Target.createTarget', { url: 'about:blank', browserContextId: this._browserContextId });
return this._browser._crPages.get(targetId)!._page;
}

Expand Down
26 changes: 24 additions & 2 deletions packages/playwright-core/src/server/electron/electron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import { eventsHelper } from '@utils/eventsHelper';
import { envArrayToObject, launchProcess } from '@utils/processLauncher';
import { ManualPromise } from '@isomorphic/manualPromise';
import { libPath } from '../../package';
import { validateBrowserContextOptions } from '../browserContext';
import { BrowserContext, validateBrowserContextOptions } from '../browserContext';
import { CRBrowser } from '../chromium/crBrowser';
import { CRConnection } from '../chromium/crConnection';
import { createHandle, CRExecutionContext } from '../chromium/crExecutionContext';
Expand All @@ -38,7 +38,6 @@ import { WebSocketTransport } from '../transport';
import { nullProgress } from '../progress';

import type { BrowserOptions, BrowserProcess } from '../browser';
import type { BrowserContext } from '../browserContext';
import type { CRBrowserContext } from '../chromium/crBrowser';
import type { CRSession } from '../chromium/crConnection';
import type { CRPage } from '../chromium/crPage';
Expand Down Expand Up @@ -86,6 +85,7 @@ export class ElectronApplication extends SdkObject {
this._nodeElectronHandlePromise.resolve(new js.JSHandle(this._nodeExecutionContext!, 'object', 'ElectronModule', remoteObject.objectId!));
});
this._nodeSession.on('Runtime.consoleAPICalled', event => this._onConsoleAPI(event));
this._browserContext.on(BrowserContext.Events.Page, page => this._onPage(page));
const appClosePromise = new Promise(f => this.once(ElectronApplication.Events.Close, f));
this._browserContext.setCustomCloseHandler(async () => {
const electronHandle = await this._nodeElectronHandlePromise;
Expand Down Expand Up @@ -138,6 +138,28 @@ export class ElectronApplication extends SdkObject {
await this._browserContext.close(progress, { reason: 'Application exited' });
}

private _onPage(page: Page) {
if (process.env.PLAYWRIGHT_ELECTRON_LEGACY_PAGE_CLOSE)
return;
// Target.closeTarget can hang on Electron when the close races a committing
// navigation. Close from the main process instead. We close the webContents
// rather than the BrowserWindow because BrowserWindow.close() always runs the
// beforeunload handler, while webContents.close() lets us opt in or out of it.
page.setCustomCloseHandler(async runBeforeUnload => {
const electronHandle = await this._nodeElectronHandlePromise;
const closed = await electronHandle.evaluate(({ webContents }, { targetId, runBeforeUnload }) => {
const wc = webContents.fromDevToolsTargetId(targetId);
if (!wc || wc.isDestroyed())
return false;
wc.close({ waitForBeforeUnload: runBeforeUnload });
return true;
}, { targetId: (page.delegate as CRPage)._targetId, runBeforeUnload }).catch(() => false);
// Fall back to the default close if the webContents could not be found.
if (!closed)
await page.delegate.closePage(runBeforeUnload);
});
}

async browserWindow(progress: Progress, page: Page): Promise<js.JSHandle<BrowserWindow>> {
// Assume CRPage as Electron is always Chromium.
const targetId = (page.delegate as CRPage)._targetId;
Expand Down
11 changes: 9 additions & 2 deletions packages/playwright-core/src/server/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ export class Page extends SdkObject<PageEventMap> {
readonly overlay: Overlay;
readonly screencast: Screencast;
_closeReason: string | undefined;
private _customCloseHandler?: (runBeforeUnload: boolean) => Promise<void>;

constructor(delegate: PageDelegate, browserContext: BrowserContext) {
super(browserContext, 'page');
Expand Down Expand Up @@ -831,19 +832,25 @@ export class Page extends SdkObject<PageEventMap> {
this._lifecycle = 'closing';
// This might throw if the browser context containing the page closes
// while we are trying to close the page.
await this.delegate.closePage(false).catch(e => debugLogger.log('error', e));
const closePage = this._customCloseHandler ?? (runBeforeUnload => this.delegate.closePage(runBeforeUnload));
await closePage(false).catch(e => debugLogger.log('error', e));
}
await this.closedPromise;
}

setCustomCloseHandler(handler: ((runBeforeUnload: boolean) => Promise<void>) | undefined) {
this._customCloseHandler = handler;
}

async runBeforeUnload(progress: Progress) {
await progress.race(this._runBeforeUnload());
}

private async _runBeforeUnload() {
// This might throw if the browser context containing the page closes
// while we are trying to close the page.
await this.delegate.closePage(true).catch(e => debugLogger.log('error', e));
const closePage = this._customCloseHandler ?? (runBeforeUnload => this.delegate.closePage(runBeforeUnload));
await closePage(true).catch(e => debugLogger.log('error', e));
}

isClosed(): boolean {
Expand Down
Loading
Loading