How to use potentiallyUnserializableValue method in Playwright Internal

Best JavaScript code snippet using playwright-internal

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

ffExecutionContext.js

Source: ffExecutionContext.js Github

copy
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.FFExecutionContext = void 0;
7
8var js = _interopRequireWildcard(require("../javascript"));
9
10var _stackTrace = require("../../utils/stackTrace");
11
12var _utilityScriptSerializers = require("../common/utilityScriptSerializers");
13
14var _protocolError = require("../common/protocolError");
15
16function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
17
18function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
19
20/**
21 * Copyright 2019 Google Inc. All rights reserved.
22 * Modifications copyright (c) Microsoft Corporation.
23 *
24 * Licensed under the Apache License, Version 2.0 (the "License");
25 * you may not use this file except in compliance with the License.
26 * You may obtain a copy of the License at
27 *
28 *     http://www.apache.org/licenses/LICENSE-2.0
29 *
30 * Unless required by applicable law or agreed to in writing, software
31 * distributed under the License is distributed on an "AS IS" BASIS,
32 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
33 * See the License for the specific language governing permissions and
34 * limitations under the License.
35 */
36class FFExecutionContext {
37  constructor(session, executionContextId) {
38    this._session = void 0;
39    this._executionContextId = void 0;
40    this._session = session;
41    this._executionContextId = executionContextId;
42  }
43
44  async rawEvaluateJSON(expression) {
45    const payload = await this._session.send('Runtime.evaluate', {
46      expression,
47      returnByValue: true,
48      executionContextId: this._executionContextId
49    }).catch(rewriteError);
50    checkException(payload.exceptionDetails);
51    return payload.result.value;
52  }
53
54  async rawEvaluateHandle(expression) {
55    const payload = await this._session.send('Runtime.evaluate', {
56      expression,
57      returnByValue: false,
58      executionContextId: this._executionContextId
59    }).catch(rewriteError);
60    checkException(payload.exceptionDetails);
61    return payload.result.objectId;
62  }
63
64  rawCallFunctionNoReply(func, ...args) {
65    this._session.send('Runtime.callFunction', {
66      functionDeclaration: func.toString(),
67      args: args.map(a => a instanceof js.JSHandle ? {
68        objectId: a._objectId
69      } : {
70        value: a
71      }),
72      returnByValue: true,
73      executionContextId: this._executionContextId
74    }).catch(() => {});
75  }
76
77  async evaluateWithArguments(expression, returnByValue, utilityScript, values, objectIds) {
78    const payload = await this._session.send('Runtime.callFunction', {
79      functionDeclaration: expression,
80      args: [{
81        objectId: utilityScript._objectId,
82        value: undefined
83      }, ...values.map(value => ({
84        value
85      })), ...objectIds.map(objectId => ({
86        objectId,
87        value: undefined
88      }))],
89      returnByValue,
90      executionContextId: this._executionContextId
91    }).catch(rewriteError);
92    checkException(payload.exceptionDetails);
93    if (returnByValue) return (0, _utilityScriptSerializers.parseEvaluationResultValue)(payload.result.value);
94    return utilityScript._context.createHandle(payload.result);
95  }
96
97  async getProperties(context, objectId) {
98    const response = await this._session.send('Runtime.getObjectProperties', {
99      executionContextId: this._executionContextId,
100      objectId
101    });
102    const result = new Map();
103
104    for (const property of response.properties) result.set(property.name, context.createHandle(property.value));
105
106    return result;
107  }
108
109  createHandle(context, remoteObject) {
110    return new js.JSHandle(context, remoteObject.subtype || remoteObject.type || '', renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
111  }
112
113  async releaseHandle(objectId) {
114    await this._session.send('Runtime.disposeObject', {
115      executionContextId: this._executionContextId,
116      objectId
117    });
118  }
119
120}
121
122exports.FFExecutionContext = FFExecutionContext;
123
124function checkException(exceptionDetails) {
125  if (!exceptionDetails) return;
126  if (exceptionDetails.value) throw new js.JavaScriptErrorInEvaluate(JSON.stringify(exceptionDetails.value));else throw new js.JavaScriptErrorInEvaluate(exceptionDetails.text + (exceptionDetails.stack ? '\n' + exceptionDetails.stack : ''));
127}
128
129function rewriteError(error) {
130  if (error.message.includes('cyclic object value') || error.message.includes('Object is not serializable')) return {
131    result: {
132      type: 'undefined',
133      value: undefined
134    }
135  };
136  if (error instanceof TypeError && error.message.startsWith('Converting circular structure to JSON')) (0, _stackTrace.rewriteErrorMessage)(error, error.message + ' Are you passing a nested JSHandle?');
137  if (!js.isJavaScriptErrorInEvaluate(error) && !(0, _protocolError.isSessionClosedError)(error)) throw new Error('Execution context was destroyed, most likely because of a navigation.');
138  throw error;
139}
140
141function potentiallyUnserializableValue(remoteObject) {
142  const value = remoteObject.value;
143  const unserializableValue = remoteObject.unserializableValue;
144  return unserializableValue ? js.parseUnserializableValue(unserializableValue) : value;
145}
146
147function renderPreview(object) {
148  if (object.type === 'undefined') return 'undefined';
149  if (object.unserializableValue) return String(object.unserializableValue);
150  if (object.type === 'symbol') return 'Symbol()';
151  if (object.subtype === 'regexp') return 'RegExp';
152  if (object.subtype === 'weakmap') return 'WeakMap';
153  if (object.subtype === 'weakset') return 'WeakSet';
154  if (object.subtype) return object.subtype[0].toUpperCase() + object.subtype.slice(1);
155  if ('value' in object) return String(object.value);
156}
Full Screen

wkExecutionContext.js

Source: wkExecutionContext.js Github

copy
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.WKExecutionContext = void 0;
7
8var js = _interopRequireWildcard(require("../javascript"));
9
10var _utilityScriptSerializers = require("../common/utilityScriptSerializers");
11
12var _protocolError = require("../common/protocolError");
13
14function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
15
16function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
17
18/**
19 * Copyright 2017 Google Inc. All rights reserved.
20 * Modifications copyright (c) Microsoft Corporation.
21 *
22 * Licensed under the Apache License, Version 2.0 (the "License");
23 * you may not use this file except in compliance with the License.
24 * You may obtain a copy of the License at
25 *
26 *     http://www.apache.org/licenses/LICENSE-2.0
27 *
28 * Unless required by applicable law or agreed to in writing, software
29 * distributed under the License is distributed on an "AS IS" BASIS,
30 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31 * See the License for the specific language governing permissions and
32 * limitations under the License.
33 */
34class WKExecutionContext {
35  constructor(session, contextId) {
36    this._session = void 0;
37    this._contextId = void 0;
38    this._session = session;
39    this._contextId = contextId;
40  }
41
42  async rawEvaluateJSON(expression) {
43    try {
44      const response = await this._session.send('Runtime.evaluate', {
45        expression,
46        contextId: this._contextId,
47        returnByValue: true
48      });
49      if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description);
50      return response.result.value;
51    } catch (error) {
52      throw rewriteError(error);
53    }
54  }
55
56  async rawEvaluateHandle(expression) {
57    try {
58      const response = await this._session.send('Runtime.evaluate', {
59        expression,
60        contextId: this._contextId,
61        returnByValue: false
62      });
63      if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description);
64      return response.result.objectId;
65    } catch (error) {
66      throw rewriteError(error);
67    }
68  }
69
70  rawCallFunctionNoReply(func, ...args) {
71    this._session.send('Runtime.callFunctionOn', {
72      functionDeclaration: func.toString(),
73      objectId: args.find(a => a instanceof js.JSHandle)._objectId,
74      arguments: args.map(a => a instanceof js.JSHandle ? {
75        objectId: a._objectId
76      } : {
77        value: a
78      }),
79      returnByValue: true,
80      emulateUserGesture: true
81    }).catch(() => {});
82  }
83
84  async evaluateWithArguments(expression, returnByValue, utilityScript, values, objectIds) {
85    try {
86      const response = await this._session.send('Runtime.callFunctionOn', {
87        functionDeclaration: expression,
88        objectId: utilityScript._objectId,
89        arguments: [{
90          objectId: utilityScript._objectId
91        }, ...values.map(value => ({
92          value
93        })), ...objectIds.map(objectId => ({
94          objectId
95        }))],
96        returnByValue,
97        emulateUserGesture: true,
98        awaitPromise: true
99      });
100      if (response.wasThrown) throw new js.JavaScriptErrorInEvaluate(response.result.description);
101      if (returnByValue) return (0, _utilityScriptSerializers.parseEvaluationResultValue)(response.result.value);
102      return utilityScript._context.createHandle(response.result);
103    } catch (error) {
104      throw rewriteError(error);
105    }
106  }
107
108  async getProperties(context, objectId) {
109    const response = await this._session.send('Runtime.getProperties', {
110      objectId,
111      ownProperties: true
112    });
113    const result = new Map();
114
115    for (const property of response.properties) {
116      if (!property.enumerable || !property.value) continue;
117      result.set(property.name, context.createHandle(property.value));
118    }
119
120    return result;
121  }
122
123  createHandle(context, remoteObject) {
124    const isPromise = remoteObject.className === 'Promise';
125    return new js.JSHandle(context, isPromise ? 'promise' : remoteObject.subtype || remoteObject.type, renderPreview(remoteObject), remoteObject.objectId, potentiallyUnserializableValue(remoteObject));
126  }
127
128  async releaseHandle(objectId) {
129    await this._session.send('Runtime.releaseObject', {
130      objectId
131    });
132  }
133
134}
135
136exports.WKExecutionContext = WKExecutionContext;
137
138function potentiallyUnserializableValue(remoteObject) {
139  const value = remoteObject.value;
140  const isUnserializable = remoteObject.type === 'number' && ['NaN', '-Infinity', 'Infinity', '-0'].includes(remoteObject.description);
141  return isUnserializable ? js.parseUnserializableValue(remoteObject.description) : value;
142}
143
144function rewriteError(error) {
145  if (!js.isJavaScriptErrorInEvaluate(error) && !(0, _protocolError.isSessionClosedError)(error)) return new Error('Execution context was destroyed, most likely because of a navigation.');
146  return error;
147}
148
149function renderPreview(object) {
150  if (object.type === 'undefined') return 'undefined';
151  if ('value' in object) return String(object.value);
152
153  if (object.description === 'Object' && object.preview) {
154    const tokens = [];
155
156    for (const {
157      name,
158      value
159    } of object.preview.properties) tokens.push(`${name}: ${value}`);
160
161    return `{${tokens.join(', ')}}`;
162  }
163
164  if (object.subtype === 'array' && object.preview) {
165    const result = [];
166
167    for (const {
168      name,
169      value
170    } of object.preview.properties) result[+name] = value;
171
172    return '[' + String(result) + ']';
173  }
174
175  return object.description;
176}
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Playwright Internal on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)