chore: contain remote objects to browser-specific code (#34890)

This commit is contained in:
Yury Semikhatsky 2025-02-21 16:52:39 -08:00 committed by GitHub
parent 6486ac006e
commit 962a752832
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 102 additions and 119 deletions

View file

@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
import { assert } from '../../utils';
import { parseEvaluationResultValue } from '../isomorphic/utilityScriptSerializers'; import { parseEvaluationResultValue } from '../isomorphic/utilityScriptSerializers';
import * as js from '../javascript'; import * as js from '../javascript';
import * as dom from '../dom'; import * as dom from '../dom';
@ -98,37 +99,26 @@ export class BidiExecutionContext implements js.ExecutionContextDelegate {
if (response.type === 'success') { if (response.type === 'success') {
if (returnByValue) if (returnByValue)
return parseEvaluationResultValue(BidiDeserializer.deserialize(response.result)); return parseEvaluationResultValue(BidiDeserializer.deserialize(response.result));
const objectId = 'handle' in response.result ? response.result.handle : undefined ; return createHandle(utilityScript._context, response.result);
return utilityScript._context.createHandle({ objectId, ...response.result });
} }
throw new js.JavaScriptErrorInEvaluate('Unexpected response type: ' + JSON.stringify(response)); throw new js.JavaScriptErrorInEvaluate('Unexpected response type: ' + JSON.stringify(response));
} }
async getProperties(context: js.ExecutionContext, objectId: js.ObjectId): Promise<Map<string, js.JSHandle>> { async getProperties(context: js.ExecutionContext, handle: js.JSHandle): Promise<Map<string, js.JSHandle>> {
const handle = this.createHandle(context, { objectId }); const names = await handle.evaluate(object => {
try { const names = [];
const names = await handle.evaluate(object => { const descriptors = Object.getOwnPropertyDescriptors(object);
const names = []; for (const name in descriptors) {
const descriptors = Object.getOwnPropertyDescriptors(object); if (descriptors[name]?.enumerable)
for (const name in descriptors) { names.push(name);
if (descriptors[name]?.enumerable) }
names.push(name); return names;
} });
return names; const values = await Promise.all(names.map(name => handle.evaluateHandle((object, name) => object[name], name)));
}); const map = new Map<string, js.JSHandle>();
const values = await Promise.all(names.map(name => handle.evaluateHandle((object, name) => object[name], name))); for (let i = 0; i < names.length; i++)
const map = new Map<string, js.JSHandle>(); map.set(names[i], values[i]);
for (let i = 0; i < names.length; i++) return map;
map.set(names[i], values[i]);
return map;
} finally {
handle.dispose();
}
}
createHandle(context: js.ExecutionContext, jsRemoteObject: js.RemoteObject): js.JSHandle {
const remoteObject: bidi.Script.RemoteValue = jsRemoteObject as bidi.Script.RemoteValue;
return new js.JSHandle(context, remoteObject.type, renderPreview(remoteObject), jsRemoteObject.objectId, remoteObjectValue(remoteObject));
} }
async releaseHandle(objectId: js.ObjectId): Promise<void> { async releaseHandle(objectId: js.ObjectId): Promise<void> {
@ -149,11 +139,11 @@ export class BidiExecutionContext implements js.ExecutionContextDelegate {
}; };
} }
async remoteObjectForNodeId(nodeId: bidi.Script.SharedReference): Promise<js.RemoteObject> { async remoteObjectForNodeId(context: dom.FrameExecutionContext, nodeId: bidi.Script.SharedReference): Promise<js.JSHandle> {
const result = await this._remoteValueForReference(nodeId); const result = await this._remoteValueForReference(nodeId);
if ('handle' in result) if (!('handle' in result))
return { objectId: result.handle!, ...result }; throw new Error('Can\'t get remote object for nodeId');
throw new Error('Can\'t get remote object for nodeId'); return createHandle(context, result);
} }
async contentFrameIdForFrame(handle: dom.ElementHandle) { async contentFrameIdForFrame(handle: dom.ElementHandle) {
@ -215,3 +205,12 @@ function remoteObjectValue(remoteObject: bidi.Script.RemoteValue): any {
return remoteObject.value; return remoteObject.value;
return undefined; return undefined;
} }
export function createHandle(context: js.ExecutionContext, remoteObject: bidi.Script.RemoteValue): js.JSHandle {
if (remoteObject.type === 'node') {
assert(context instanceof dom.FrameExecutionContext);
return new dom.ElementHandle(context, remoteObject.handle!);
}
const objectId = 'handle' in remoteObject ? remoteObject.handle : undefined;
return new js.JSHandle(context, remoteObject.type, renderPreview(remoteObject), objectId, remoteObjectValue(remoteObject));
}

View file

@ -20,7 +20,7 @@ import { BrowserContext } from '../browserContext';
import * as dialog from '../dialog'; import * as dialog from '../dialog';
import * as dom from '../dom'; import * as dom from '../dom';
import { Page } from '../page'; import { Page } from '../page';
import { BidiExecutionContext } from './bidiExecutionContext'; import { BidiExecutionContext, createHandle } from './bidiExecutionContext';
import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './bidiInput'; import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './bidiInput';
import { BidiNetworkManager } from './bidiNetworkManager'; import { BidiNetworkManager } from './bidiNetworkManager';
import { BidiPDF } from './bidiPdf'; import { BidiPDF } from './bidiPdf';
@ -130,7 +130,6 @@ export class BidiPage implements PageDelegate {
const frame = this._page._frameManager.frame(realmInfo.context); const frame = this._page._frameManager.frame(realmInfo.context);
if (!frame) if (!frame)
return; return;
const delegate = new BidiExecutionContext(this._session, realmInfo);
let worldName: types.World; let worldName: types.World;
if (!realmInfo.sandbox) { if (!realmInfo.sandbox) {
worldName = 'main'; worldName = 'main';
@ -141,6 +140,7 @@ export class BidiPage implements PageDelegate {
} else { } else {
return; return;
} }
const delegate = new BidiExecutionContext(this._session, realmInfo);
const context = new dom.FrameExecutionContext(delegate, frame, worldName); const context = new dom.FrameExecutionContext(delegate, frame, worldName);
(context as any)[contextDelegateSymbol] = delegate; (context as any)[contextDelegateSymbol] = delegate;
frame._contextCreated(worldName, context); frame._contextCreated(worldName, context);
@ -242,7 +242,7 @@ export class BidiPage implements PageDelegate {
return; return;
const callFrame = params.stackTrace?.callFrames[0]; const callFrame = params.stackTrace?.callFrames[0];
const location = callFrame ?? { url: '', lineNumber: 1, columnNumber: 1 }; const location = callFrame ?? { url: '', lineNumber: 1, columnNumber: 1 };
this._page._addConsoleMessage(entry.method, entry.args.map(arg => context.createHandle({ objectId: (arg as any).handle, ...arg })), location, params.text || undefined); this._page._addConsoleMessage(entry.method, entry.args.map(arg => createHandle(context, arg)), location, params.text || undefined);
} }
async navigateFrame(frame: frames.Frame, url: string, referrer: string | undefined): Promise<frames.GotoResult> { async navigateFrame(frame: frames.Frame, url: string, referrer: string | undefined): Promise<frames.GotoResult> {
@ -431,10 +431,6 @@ export class BidiPage implements PageDelegate {
return executionContext.frameIdForWindowHandle(windowHandle); return executionContext.frameIdForWindowHandle(windowHandle);
} }
isElementHandle(remoteObject: bidi.Script.RemoteValue): boolean {
return remoteObject.type === 'node';
}
async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> { async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
const box = await handle.evaluate(element => { const box = await handle.evaluate(element => {
if (!(element instanceof Element)) if (!(element instanceof Element))
@ -532,10 +528,7 @@ export class BidiPage implements PageDelegate {
const fromContext = toBidiExecutionContext(handle._context); const fromContext = toBidiExecutionContext(handle._context);
const nodeId = await fromContext.nodeIdForElementHandle(handle); const nodeId = await fromContext.nodeIdForElementHandle(handle);
const executionContext = toBidiExecutionContext(to); const executionContext = toBidiExecutionContext(to);
const objectId = await executionContext.remoteObjectForNodeId(nodeId); return await executionContext.remoteObjectForNodeId(to, nodeId) as dom.ElementHandle<T>;
if (objectId)
return to.createHandle(objectId) as dom.ElementHandle<T>;
throw new Error('Failed to adopt element handle.');
} }
async getAccessibilityTree(needle?: dom.ElementHandle): Promise<{tree: accessibility.AXNode, needle: accessibility.AXNode | null}> { async getAccessibilityTree(needle?: dom.ElementHandle): Promise<{tree: accessibility.AXNode, needle: accessibility.AXNode | null}> {

View file

@ -15,10 +15,12 @@
* limitations under the License. * limitations under the License.
*/ */
import { assert } from '../../utils/isomorphic/assert';
import { getExceptionMessage, releaseObject } from './crProtocolHelper'; import { getExceptionMessage, releaseObject } from './crProtocolHelper';
import { rewriteErrorMessage } from '../../utils/isomorphic/stackTrace'; import { rewriteErrorMessage } from '../../utils/isomorphic/stackTrace';
import { parseEvaluationResultValue } from '../isomorphic/utilityScriptSerializers'; import { parseEvaluationResultValue } from '../isomorphic/utilityScriptSerializers';
import * as js from '../javascript'; import * as js from '../javascript';
import * as dom from '../dom';
import { isSessionClosedError } from '../protocolError'; import { isSessionClosedError } from '../protocolError';
import type { CRSession } from './crConnection'; import type { CRSession } from './crConnection';
@ -69,27 +71,23 @@ export class CRExecutionContext implements js.ExecutionContextDelegate {
}).catch(rewriteError); }).catch(rewriteError);
if (exceptionDetails) if (exceptionDetails)
throw new js.JavaScriptErrorInEvaluate(getExceptionMessage(exceptionDetails)); throw new js.JavaScriptErrorInEvaluate(getExceptionMessage(exceptionDetails));
return returnByValue ? parseEvaluationResultValue(remoteObject.value) : utilityScript._context.createHandle(remoteObject); return returnByValue ? parseEvaluationResultValue(remoteObject.value) : createHandle(utilityScript._context, remoteObject);
} }
async getProperties(context: js.ExecutionContext, objectId: js.ObjectId): Promise<Map<string, js.JSHandle>> { async getProperties(context: js.ExecutionContext, object: js.JSHandle): Promise<Map<string, js.JSHandle>> {
const response = await this._client.send('Runtime.getProperties', { const response = await this._client.send('Runtime.getProperties', {
objectId, objectId: object._objectId!,
ownProperties: true ownProperties: true
}); });
const result = new Map(); const result = new Map();
for (const property of response.result) { for (const property of response.result) {
if (!property.enumerable || !property.value) if (!property.enumerable || !property.value)
continue; continue;
result.set(property.name, context.createHandle(property.value)); result.set(property.name, createHandle(object._context, property.value));
} }
return result; return result;
} }
createHandle(context: js.ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject): js.JSHandle {
return new js.JSHandle(context, remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
}
async releaseHandle(objectId: js.ObjectId): Promise<void> { async releaseHandle(objectId: js.ObjectId): Promise<void> {
await releaseObject(this._client, objectId); await releaseObject(this._client, objectId);
} }
@ -132,3 +130,11 @@ function renderPreview(object: Protocol.Runtime.RemoteObject): string | undefine
return js.sparseArrayToString(object.preview.properties); return js.sparseArrayToString(object.preview.properties);
return object.description; return object.description;
} }
export function createHandle(context: js.ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject): js.JSHandle {
if (remoteObject.subtype === 'node') {
assert(context instanceof dom.FrameExecutionContext);
return new dom.ElementHandle(context, remoteObject.objectId!);
}
return new js.JSHandle(context, remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
}

View file

@ -33,7 +33,7 @@ import { getAccessibilityTree } from './crAccessibility';
import { CRBrowserContext } from './crBrowser'; import { CRBrowserContext } from './crBrowser';
import { CRCoverage } from './crCoverage'; import { CRCoverage } from './crCoverage';
import { DragManager } from './crDragDrop'; import { DragManager } from './crDragDrop';
import { CRExecutionContext } from './crExecutionContext'; import { createHandle, CRExecutionContext } from './crExecutionContext';
import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './crInput'; import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './crInput';
import { CRNetworkManager } from './crNetworkManager'; import { CRNetworkManager } from './crNetworkManager';
import { CRPDF } from './crPdf'; import { CRPDF } from './crPdf';
@ -281,10 +281,6 @@ export class CRPage implements PageDelegate {
return this._sessionForHandle(handle)._getOwnerFrame(handle); return this._sessionForHandle(handle)._getOwnerFrame(handle);
} }
isElementHandle(remoteObject: any): boolean {
return (remoteObject as Protocol.Runtime.RemoteObject).subtype === 'node';
}
async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> { async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
return this._sessionForHandle(handle)._getBoundingBox(handle); return this._sessionForHandle(handle)._getBoundingBox(handle);
} }
@ -739,7 +735,7 @@ class FrameSession {
session.on('Target.attachedToTarget', event => this._onAttachedToTarget(event)); session.on('Target.attachedToTarget', event => this._onAttachedToTarget(event));
session.on('Target.detachedFromTarget', event => this._onDetachedFromTarget(event)); session.on('Target.detachedFromTarget', event => this._onDetachedFromTarget(event));
session.on('Runtime.consoleAPICalled', event => { session.on('Runtime.consoleAPICalled', event => {
const args = event.args.map(o => worker._existingExecutionContext!.createHandle(o)); const args = event.args.map(o => createHandle(worker._existingExecutionContext!, o));
this._page._addConsoleMessage(event.type, args, toConsoleMessageLocation(event.stackTrace)); this._page._addConsoleMessage(event.type, args, toConsoleMessageLocation(event.stackTrace));
}); });
session.on('Runtime.exceptionThrown', exception => this._page.emitOnContextOnceInitialized(BrowserContext.Events.PageError, exceptionToError(exception.exceptionDetails), this._page)); session.on('Runtime.exceptionThrown', exception => this._page.emitOnContextOnceInitialized(BrowserContext.Events.PageError, exceptionToError(exception.exceptionDetails), this._page));
@ -802,7 +798,7 @@ class FrameSession {
const context = this._contextIdToContext.get(event.executionContextId); const context = this._contextIdToContext.get(event.executionContextId);
if (!context) if (!context)
return; return;
const values = event.args.map(arg => context.createHandle(arg)); const values = event.args.map(arg => createHandle(context, arg));
this._page._addConsoleMessage(event.type, values, toConsoleMessageLocation(event.stackTrace)); this._page._addConsoleMessage(event.type, values, toConsoleMessageLocation(event.stackTrace));
} }
@ -1171,7 +1167,7 @@ class FrameSession {
}); });
if (!result || result.object.subtype === 'null') if (!result || result.object.subtype === 'null')
throw new Error(dom.kUnableToAdoptErrorMessage); throw new Error(dom.kUnableToAdoptErrorMessage);
return to.createHandle(result.object).asElement()!; return createHandle(to, result.object).asElement()!;
} }
} }

View file

@ -83,12 +83,6 @@ export class FrameExecutionContext extends js.ExecutionContext {
return js.evaluateExpression(this, expression, { ...options, returnByValue: false }, arg); return js.evaluateExpression(this, expression, { ...options, returnByValue: false }, arg);
} }
override createHandle(remoteObject: js.RemoteObject): js.JSHandle {
if (this.frame._page._delegate.isElementHandle(remoteObject))
return new ElementHandle(this, remoteObject.objectId!);
return super.createHandle(remoteObject);
}
injectedScript(): Promise<js.JSHandle<InjectedScript>> { injectedScript(): Promise<js.JSHandle<InjectedScript>> {
if (!this._injectedScriptPromise) { if (!this._injectedScriptPromise) {
const custom: string[] = []; const custom: string[] = [];
@ -124,7 +118,7 @@ export class ElementHandle<T extends Node = Node> extends js.JSHandle<T> {
declare readonly _objectId: string; declare readonly _objectId: string;
readonly _frame: frames.Frame; readonly _frame: frames.Frame;
constructor(context: FrameExecutionContext, objectId: string) { constructor(context: FrameExecutionContext, objectId: js.ObjectId) {
super(context, 'node', undefined, objectId); super(context, 'node', undefined, objectId);
this._page = context.frame._page; this._page = context.frame._page;
this._frame = context.frame; this._frame = context.frame;

View file

@ -27,7 +27,7 @@ import { eventsHelper } from '../utils/eventsHelper';
import { validateBrowserContextOptions } from '../browserContext'; import { validateBrowserContextOptions } from '../browserContext';
import { CRBrowser } from '../chromium/crBrowser'; import { CRBrowser } from '../chromium/crBrowser';
import { CRConnection } from '../chromium/crConnection'; import { CRConnection } from '../chromium/crConnection';
import { CRExecutionContext } from '../chromium/crExecutionContext'; import { createHandle, CRExecutionContext } from '../chromium/crExecutionContext';
import { toConsoleMessageLocation } from '../chromium/crProtocolHelper'; import { toConsoleMessageLocation } from '../chromium/crProtocolHelper';
import { ConsoleMessage } from '../console'; import { ConsoleMessage } from '../console';
import { helper } from '../helper'; import { helper } from '../helper';
@ -116,7 +116,7 @@ export class ElectronApplication extends SdkObject {
} }
if (!this._nodeExecutionContext) if (!this._nodeExecutionContext)
return; return;
const args = event.args.map(arg => this._nodeExecutionContext!.createHandle(arg)); const args = event.args.map(arg => createHandle(this._nodeExecutionContext!, arg));
const message = new ConsoleMessage(null, event.type, undefined, args, toConsoleMessageLocation(event.stackTrace)); const message = new ConsoleMessage(null, event.type, undefined, args, toConsoleMessageLocation(event.stackTrace));
this.emit(ElectronApplication.Events.Console, message); this.emit(ElectronApplication.Events.Console, message);
} }

View file

@ -15,9 +15,11 @@
* limitations under the License. * limitations under the License.
*/ */
import { assert } from '../../utils/isomorphic/assert';
import { rewriteErrorMessage } from '../../utils/isomorphic/stackTrace'; import { rewriteErrorMessage } from '../../utils/isomorphic/stackTrace';
import { parseEvaluationResultValue } from '../isomorphic/utilityScriptSerializers'; import { parseEvaluationResultValue } from '../isomorphic/utilityScriptSerializers';
import * as js from '../javascript'; import * as js from '../javascript';
import * as dom from '../dom';
import { isSessionClosedError } from '../protocolError'; import { isSessionClosedError } from '../protocolError';
import type { FFSession } from './ffConnection'; import type { FFSession } from './ffConnection';
@ -66,24 +68,20 @@ export class FFExecutionContext implements js.ExecutionContextDelegate {
checkException(payload.exceptionDetails); checkException(payload.exceptionDetails);
if (returnByValue) if (returnByValue)
return parseEvaluationResultValue(payload.result!.value); return parseEvaluationResultValue(payload.result!.value);
return utilityScript._context.createHandle(payload.result!); return createHandle(utilityScript._context, payload.result!);
} }
async getProperties(context: js.ExecutionContext, objectId: js.ObjectId): Promise<Map<string, js.JSHandle>> { async getProperties(context: js.ExecutionContext, object: js.JSHandle): Promise<Map<string, js.JSHandle>> {
const response = await this._session.send('Runtime.getObjectProperties', { const response = await this._session.send('Runtime.getObjectProperties', {
executionContextId: this._executionContextId, executionContextId: this._executionContextId,
objectId, objectId: object._objectId!,
}); });
const result = new Map(); const result = new Map();
for (const property of response.properties) for (const property of response.properties)
result.set(property.name, context.createHandle(property.value)); result.set(property.name, createHandle(context, property.value));
return result; return result;
} }
createHandle(context: js.ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject): js.JSHandle {
return new js.JSHandle(context, remoteObject.subtype || remoteObject.type || '', renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
}
async releaseHandle(objectId: js.ObjectId): Promise<void> { async releaseHandle(objectId: js.ObjectId): Promise<void> {
await this._session.send('Runtime.disposeObject', { await this._session.send('Runtime.disposeObject', {
executionContextId: this._executionContextId, executionContextId: this._executionContextId,
@ -135,3 +133,11 @@ function renderPreview(object: Protocol.Runtime.RemoteObject): string | undefine
if ('value' in object) if ('value' in object)
return String(object.value); return String(object.value);
} }
export function createHandle(context: js.ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject): js.JSHandle {
if (remoteObject.subtype === 'node') {
assert(context instanceof dom.FrameExecutionContext);
return new dom.ElementHandle(context, remoteObject.objectId!);
}
return new js.JSHandle(context, remoteObject.subtype || remoteObject.type || '', renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
}

View file

@ -22,7 +22,7 @@ import { InitScript } from '../page';
import { Page, Worker } from '../page'; import { Page, Worker } from '../page';
import { getAccessibilityTree } from './ffAccessibility'; import { getAccessibilityTree } from './ffAccessibility';
import { FFSession } from './ffConnection'; import { FFSession } from './ffConnection';
import { FFExecutionContext } from './ffExecutionContext'; import { createHandle, FFExecutionContext } from './ffExecutionContext';
import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './ffInput'; import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './ffInput';
import { FFNetworkManager } from './ffNetworkManager'; import { FFNetworkManager } from './ffNetworkManager';
import { debugLogger } from '../utils/debugLogger'; import { debugLogger } from '../utils/debugLogger';
@ -234,7 +234,7 @@ export class FFPage implements PageDelegate {
if (!context) if (!context)
return; return;
// Juggler reports 'warn' for some internal messages generated by the browser. // Juggler reports 'warn' for some internal messages generated by the browser.
this._page._addConsoleMessage(type === 'warn' ? 'warning' : type, args.map(arg => context.createHandle(arg)), location); this._page._addConsoleMessage(type === 'warn' ? 'warning' : type, args.map(arg => createHandle(context, arg)), location);
} }
_onDialogOpened(params: Protocol.Page.dialogOpenedPayload) { _onDialogOpened(params: Protocol.Page.dialogOpenedPayload) {
@ -262,7 +262,7 @@ export class FFPage implements PageDelegate {
const context = this._contextIdToContext.get(executionContextId); const context = this._contextIdToContext.get(executionContextId);
if (!context) if (!context)
return; return;
const handle = context.createHandle(element).asElement()!; const handle = createHandle(context, element).asElement()!;
await this._page._onFileChooserOpened(handle); await this._page._onFileChooserOpened(handle);
} }
@ -286,7 +286,7 @@ export class FFPage implements PageDelegate {
workerSession.on('Runtime.console', event => { workerSession.on('Runtime.console', event => {
const { type, args, location } = event; const { type, args, location } = event;
const context = worker._existingExecutionContext!; const context = worker._existingExecutionContext!;
this._page._addConsoleMessage(type, args.map(arg => context.createHandle(arg)), location); this._page._addConsoleMessage(type, args.map(arg => createHandle(context, arg)), location);
}); });
// Note: we receive worker exceptions directly from the page. // Note: we receive worker exceptions directly from the page.
} }
@ -443,10 +443,6 @@ export class FFPage implements PageDelegate {
return ownerFrameId || null; return ownerFrameId || null;
} }
isElementHandle(remoteObject: any): boolean {
return remoteObject.subtype === 'node';
}
async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> { async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
const quads = await this.getContentQuads(handle); const quads = await this.getContentQuads(handle);
if (!quads || !quads.length) if (!quads || !quads.length)
@ -535,7 +531,7 @@ export class FFPage implements PageDelegate {
}); });
if (!result.remoteObject) if (!result.remoteObject)
throw new Error(dom.kUnableToAdoptErrorMessage); throw new Error(dom.kUnableToAdoptErrorMessage);
return to.createHandle(result.remoteObject) as dom.ElementHandle<T>; return createHandle(to, result.remoteObject) as dom.ElementHandle<T>;
} }
async getAccessibilityTree(needle?: dom.ElementHandle) { async getAccessibilityTree(needle?: dom.ElementHandle) {
@ -564,7 +560,7 @@ export class FFPage implements PageDelegate {
}); });
if (!result.remoteObject) if (!result.remoteObject)
throw new Error('Frame has been detached.'); throw new Error('Frame has been detached.');
return context.createHandle(result.remoteObject) as dom.ElementHandle; return createHandle(context, result.remoteObject) as dom.ElementHandle;
} }
shouldToggleStyleSheetToSyncAnimations(): boolean { shouldToggleStyleSheetToSyncAnimations(): boolean {

View file

@ -24,10 +24,6 @@ import type * as dom from './dom';
import type { UtilityScript } from './injected/utilityScript'; import type { UtilityScript } from './injected/utilityScript';
export type ObjectId = string; export type ObjectId = string;
export type RemoteObject = {
objectId?: ObjectId,
value?: any
};
interface TaggedAsJSHandle<T> { interface TaggedAsJSHandle<T> {
__jshandle: T; __jshandle: T;
@ -55,8 +51,7 @@ export interface ExecutionContextDelegate {
rawEvaluateJSON(expression: string): Promise<any>; rawEvaluateJSON(expression: string): Promise<any>;
rawEvaluateHandle(expression: string): Promise<ObjectId>; rawEvaluateHandle(expression: string): Promise<ObjectId>;
evaluateWithArguments(expression: string, returnByValue: boolean, utilityScript: JSHandle<any>, values: any[], objectIds: ObjectId[]): Promise<any>; evaluateWithArguments(expression: string, returnByValue: boolean, utilityScript: JSHandle<any>, values: any[], objectIds: ObjectId[]): Promise<any>;
getProperties(context: ExecutionContext, objectId: ObjectId): Promise<Map<string, JSHandle>>; getProperties(context: ExecutionContext, object: JSHandle): Promise<Map<string, JSHandle>>;
createHandle(context: ExecutionContext, remoteObject: RemoteObject): JSHandle;
releaseHandle(objectId: ObjectId): Promise<void>; releaseHandle(objectId: ObjectId): Promise<void>;
} }
@ -93,12 +88,8 @@ export class ExecutionContext extends SdkObject {
return this._raceAgainstContextDestroyed(this._delegate.evaluateWithArguments(expression, returnByValue, utilityScript, values, objectIds)); return this._raceAgainstContextDestroyed(this._delegate.evaluateWithArguments(expression, returnByValue, utilityScript, values, objectIds));
} }
getProperties(context: ExecutionContext, objectId: ObjectId): Promise<Map<string, JSHandle>> { getProperties(context: ExecutionContext, object: JSHandle): Promise<Map<string, JSHandle>> {
return this._raceAgainstContextDestroyed(this._delegate.getProperties(context, objectId)); return this._raceAgainstContextDestroyed(this._delegate.getProperties(context, object));
}
createHandle(remoteObject: RemoteObject): JSHandle {
return this._delegate.createHandle(this, remoteObject);
} }
releaseHandle(objectId: ObjectId): Promise<void> { releaseHandle(objectId: ObjectId): Promise<void> {
@ -183,7 +174,7 @@ export class JSHandle<T = any> extends SdkObject {
async getProperties(): Promise<Map<string, JSHandle>> { async getProperties(): Promise<Map<string, JSHandle>> {
if (!this._objectId) if (!this._objectId)
return new Map(); return new Map();
return this._context.getProperties(this._context, this._objectId); return this._context.getProperties(this._context, this);
} }
rawValue() { rawValue() {

View file

@ -75,7 +75,6 @@ export interface PageDelegate {
setBackgroundColor(color?: { r: number; g: number; b: number; a: number; }): Promise<void>; setBackgroundColor(color?: { r: number; g: number; b: number; a: number; }): Promise<void>;
takeScreenshot(progress: Progress, format: string, documentRect: types.Rect | undefined, viewportRect: types.Rect | undefined, quality: number | undefined, fitsViewport: boolean, scale: 'css' | 'device'): Promise<Buffer>; takeScreenshot(progress: Progress, format: string, documentRect: types.Rect | undefined, viewportRect: types.Rect | undefined, quality: number | undefined, fitsViewport: boolean, scale: 'css' | 'device'): Promise<Buffer>;
isElementHandle(remoteObject: any): boolean;
adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>>; adoptElementHandle<T extends Node>(handle: dom.ElementHandle<T>, to: dom.FrameExecutionContext): Promise<dom.ElementHandle<T>>;
getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null>; // Only called for frame owner elements. getContentFrame(handle: dom.ElementHandle): Promise<frames.Frame | null>; // Only called for frame owner elements.
getOwnerFrame(handle: dom.ElementHandle): Promise<string | null>; // Returns frameId. getOwnerFrame(handle: dom.ElementHandle): Promise<string | null>; // Returns frameId.
@ -834,6 +833,7 @@ export class Worker extends SdkObject {
_createExecutionContext(delegate: js.ExecutionContextDelegate) { _createExecutionContext(delegate: js.ExecutionContextDelegate) {
this._existingExecutionContext = new js.ExecutionContext(this, delegate, 'worker'); this._existingExecutionContext = new js.ExecutionContext(this, delegate, 'worker');
this._executionContextCallback(this._existingExecutionContext); this._executionContextCallback(this._existingExecutionContext);
return this._existingExecutionContext;
} }
url(): string { url(): string {

View file

@ -17,7 +17,9 @@
import { parseEvaluationResultValue } from '../isomorphic/utilityScriptSerializers'; import { parseEvaluationResultValue } from '../isomorphic/utilityScriptSerializers';
import * as js from '../javascript'; import * as js from '../javascript';
import * as dom from '../dom';
import { isSessionClosedError } from '../protocolError'; import { isSessionClosedError } from '../protocolError';
import { assert } from '../../utils/isomorphic/assert';
import type { Protocol } from './protocol'; import type { Protocol } from './protocol';
import type { WKSession } from './wkConnection'; import type { WKSession } from './wkConnection';
@ -79,31 +81,26 @@ export class WKExecutionContext implements js.ExecutionContextDelegate {
throw new js.JavaScriptErrorInEvaluate(response.result.description); throw new js.JavaScriptErrorInEvaluate(response.result.description);
if (returnByValue) if (returnByValue)
return parseEvaluationResultValue(response.result.value); return parseEvaluationResultValue(response.result.value);
return utilityScript._context.createHandle(response.result); return createHandle(utilityScript._context, response.result);
} catch (error) { } catch (error) {
throw rewriteError(error); throw rewriteError(error);
} }
} }
async getProperties(context: js.ExecutionContext, objectId: js.ObjectId): Promise<Map<string, js.JSHandle>> { async getProperties(context: js.ExecutionContext, object: js.JSHandle): Promise<Map<string, js.JSHandle>> {
const response = await this._session.send('Runtime.getProperties', { const response = await this._session.send('Runtime.getProperties', {
objectId, objectId: object._objectId!,
ownProperties: true ownProperties: true
}); });
const result = new Map(); const result = new Map();
for (const property of response.properties) { for (const property of response.properties) {
if (!property.enumerable || !property.value) if (!property.enumerable || !property.value)
continue; continue;
result.set(property.name, context.createHandle(property.value)); result.set(property.name, createHandle(context, property.value));
} }
return result; return result;
} }
createHandle(context: js.ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject): js.JSHandle {
const isPromise = remoteObject.className === 'Promise';
return new js.JSHandle(context, isPromise ? 'promise' : remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
}
async releaseHandle(objectId: js.ObjectId): Promise<void> { async releaseHandle(objectId: js.ObjectId): Promise<void> {
await this._session.send('Runtime.releaseObject', { objectId }); await this._session.send('Runtime.releaseObject', { objectId });
} }
@ -139,3 +136,12 @@ function renderPreview(object: Protocol.Runtime.RemoteObject): string | undefine
return js.sparseArrayToString(object.preview.properties!); return js.sparseArrayToString(object.preview.properties!);
return object.description; return object.description;
} }
export function createHandle(context: js.ExecutionContext, remoteObject: Protocol.Runtime.RemoteObject): js.JSHandle {
if (remoteObject.subtype === 'node') {
assert(context instanceof dom.FrameExecutionContext);
return new dom.ElementHandle(context as dom.FrameExecutionContext, remoteObject.objectId!);
}
const isPromise = remoteObject.className === 'Promise';
return new js.JSHandle(context, isPromise ? 'promise' : remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
}

View file

@ -34,7 +34,7 @@ import { PageBinding } from '../page';
import { Page } from '../page'; import { Page } from '../page';
import { getAccessibilityTree } from './wkAccessibility'; import { getAccessibilityTree } from './wkAccessibility';
import { WKSession } from './wkConnection'; import { WKSession } from './wkConnection';
import { WKExecutionContext } from './wkExecutionContext'; import { createHandle, WKExecutionContext } from './wkExecutionContext';
import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './wkInput'; import { RawKeyboardImpl, RawMouseImpl, RawTouchscreenImpl } from './wkInput';
import { WKInterceptableRequest, WKRouteImpl } from './wkInterceptableRequest'; import { WKInterceptableRequest, WKRouteImpl } from './wkInterceptableRequest';
import { WKProvisionalPage } from './wkProvisionalPage'; import { WKProvisionalPage } from './wkProvisionalPage';
@ -562,7 +562,7 @@ export class WKPage implements PageDelegate {
} }
if (!context) if (!context)
return; return;
handles.push(context.createHandle(p)); handles.push(createHandle(context, p));
} }
this._lastConsoleMessage = { this._lastConsoleMessage = {
derivedType, derivedType,
@ -611,7 +611,7 @@ export class WKPage implements PageDelegate {
let handle; let handle;
try { try {
const context = await this._page._frameManager.frame(event.frameId)!._mainContext(); const context = await this._page._frameManager.frame(event.frameId)!._mainContext();
handle = context.createHandle(event.element).asElement()!; handle = createHandle(context, event.element).asElement()!;
} catch (e) { } catch (e) {
// During async processing, frame/context may go away. We should not throw. // During async processing, frame/context may go away. We should not throw.
return; return;
@ -869,10 +869,6 @@ export class WKPage implements PageDelegate {
return nodeInfo.ownerFrameId || null; return nodeInfo.ownerFrameId || null;
} }
isElementHandle(remoteObject: any): boolean {
return (remoteObject as Protocol.Runtime.RemoteObject).subtype === 'node';
}
async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> { async getBoundingBox(handle: dom.ElementHandle): Promise<types.Rect | null> {
const quads = await this.getContentQuads(handle); const quads = await this.getContentQuads(handle);
if (!quads || !quads.length) if (!quads || !quads.length)
@ -962,7 +958,7 @@ export class WKPage implements PageDelegate {
}); });
if (!result || result.object.subtype === 'null') if (!result || result.object.subtype === 'null')
throw new Error(dom.kUnableToAdoptErrorMessage); throw new Error(dom.kUnableToAdoptErrorMessage);
return to.createHandle(result.object) as dom.ElementHandle<T>; return createHandle(to, result.object) as dom.ElementHandle<T>;
} }
async getAccessibilityTree(needle?: dom.ElementHandle): Promise<{tree: accessibility.AXNode, needle: accessibility.AXNode | null}> { async getAccessibilityTree(needle?: dom.ElementHandle): Promise<{tree: accessibility.AXNode, needle: accessibility.AXNode | null}> {
@ -986,7 +982,7 @@ export class WKPage implements PageDelegate {
}); });
if (!result || result.object.subtype === 'null') if (!result || result.object.subtype === 'null')
throw new Error('Frame has been detached.'); throw new Error('Frame has been detached.');
return context.createHandle(result.object) as dom.ElementHandle; return createHandle(context, result.object) as dom.ElementHandle;
} }
private _maybeCancelCoopNavigationRequest(provisionalPage: WKProvisionalPage) { private _maybeCancelCoopNavigationRequest(provisionalPage: WKProvisionalPage) {

View file

@ -17,7 +17,7 @@
import { eventsHelper } from '../utils/eventsHelper'; import { eventsHelper } from '../utils/eventsHelper';
import { Worker } from '../page'; import { Worker } from '../page';
import { WKSession } from './wkConnection'; import { WKSession } from './wkConnection';
import { WKExecutionContext } from './wkExecutionContext'; import { createHandle, WKExecutionContext } from './wkExecutionContext';
import type { Protocol } from './protocol'; import type { Protocol } from './protocol';
import type { RegisteredListener } from '../utils/eventsHelper'; import type { RegisteredListener } from '../utils/eventsHelper';
@ -95,7 +95,7 @@ export class WKWorkers {
derivedType = 'timeEnd'; derivedType = 'timeEnd';
const handles = (parameters || []).map(p => { const handles = (parameters || []).map(p => {
return worker._existingExecutionContext!.createHandle(p); return createHandle(worker._existingExecutionContext!, p);
}); });
const location: types.ConsoleMessageLocation = { const location: types.ConsoleMessageLocation = {
url: url || '', url: url || '',