How to use normalizeEvaluationExpression 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.

javascript.js

Source: javascript.js Github

copy
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.evaluate = evaluate;
7exports.evaluateExpression = evaluateExpression;
8exports.evaluateExpressionAndWaitForSignals = evaluateExpressionAndWaitForSignals;
9exports.parseUnserializableValue = parseUnserializableValue;
10exports.normalizeEvaluationExpression = normalizeEvaluationExpression;
11exports.isJavaScriptErrorInEvaluate = isJavaScriptErrorInEvaluate;
12exports.JavaScriptErrorInEvaluate = exports.JSHandle = exports.ExecutionContext = void 0;
13
14var utilityScriptSource = _interopRequireWildcard(require("../generated/utilityScriptSource"));
15
16var _utilityScriptSerializers = require("./common/utilityScriptSerializers");
17
18var _instrumentation = require("./instrumentation");
19
20function _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); }
21
22function _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; }
23
24/**
25 * Copyright (c) Microsoft Corporation.
26 *
27 * Licensed under the Apache License, Version 2.0 (the "License");
28 * you may not use this file except in compliance with the License.
29 * You may obtain a copy of the License at
30 *
31 * http://www.apache.org/licenses/LICENSE-2.0
32 *
33 * Unless required by applicable law or agreed to in writing, software
34 * distributed under the License is distributed on an "AS IS" BASIS,
35 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
36 * See the License for the specific language governing permissions and
37 * limitations under the License.
38 */
39class ExecutionContext extends _instrumentation.SdkObject {
40  constructor(parent, delegate) {
41    super(parent, 'execution-context');
42    this._delegate = void 0;
43    this._utilityScriptPromise = void 0;
44    this._delegate = delegate;
45  }
46
47  async waitForSignalsCreatedBy(action) {
48    return action();
49  }
50
51  adoptIfNeeded(handle) {
52    return null;
53  }
54
55  utilityScript() {
56    if (!this._utilityScriptPromise) {
57      const source = `
58      (() => {
59        ${utilityScriptSource.source}
60        return new pwExport();
61      })();`;
62      this._utilityScriptPromise = this._delegate.rawEvaluateHandle(source).then(objectId => new JSHandle(this, 'object', undefined, objectId));
63    }
64
65    return this._utilityScriptPromise;
66  }
67
68  createHandle(remoteObject) {
69    return this._delegate.createHandle(this, remoteObject);
70  }
71
72  async rawEvaluateJSON(expression) {
73    return await this._delegate.rawEvaluateJSON(expression);
74  }
75
76  async doSlowMo() {// overridden in FrameExecutionContext
77  }
78
79}
80
81exports.ExecutionContext = ExecutionContext;
82
83class JSHandle extends _instrumentation.SdkObject {
84  constructor(context, type, preview, objectId, value) {
85    super(context, 'handle');
86    this._context = void 0;
87    this._disposed = false;
88    this._objectId = void 0;
89    this._value = void 0;
90    this._objectType = void 0;
91    this._preview = void 0;
92    this._previewCallback = void 0;
93    this._context = context;
94    this._objectId = objectId;
95    this._value = value;
96    this._objectType = type;
97    this._preview = this._objectId ? preview || `[email protected]${this._objectType}` : String(value);
98  }
99
100  callFunctionNoReply(func, arg) {
101    this._context._delegate.rawCallFunctionNoReply(func, this, arg);
102  }
103
104  async evaluate(pageFunction, arg) {
105    return evaluate(this._context, true
106    /* returnByValue */
107    , pageFunction, this, arg);
108  }
109
110  async evaluateHandle(pageFunction, arg) {
111    return evaluate(this._context, false
112    /* returnByValue */
113    , pageFunction, this, arg);
114  }
115
116  async evaluateExpressionAndWaitForSignals(expression, isFunction, returnByValue, arg) {
117    const value = await evaluateExpressionAndWaitForSignals(this._context, returnByValue, expression, isFunction, this, arg);
118    await this._context.doSlowMo();
119    return value;
120  }
121
122  async getProperty(propertyName) {
123    const objectHandle = await this.evaluateHandle((object, propertyName) => {
124      const result = {
125        __proto__: null
126      };
127      result[propertyName] = object[propertyName];
128      return result;
129    }, propertyName);
130    const properties = await objectHandle.getProperties();
131    const result = properties.get(propertyName);
132    objectHandle.dispose();
133    return result;
134  }
135
136  async getProperties() {
137    if (!this._objectId) return new Map();
138    return this._context._delegate.getProperties(this._context, this._objectId);
139  }
140
141  rawValue() {
142    return this._value;
143  }
144
145  async jsonValue() {
146    if (!this._objectId) return this._value;
147    const utilityScript = await this._context.utilityScript();
148    const script = `(utilityScript, ...args) => utilityScript.jsonValue(...args)`;
149    return this._context._delegate.evaluateWithArguments(script, true, utilityScript, [true], [this._objectId]);
150  }
151
152  asElement() {
153    return null;
154  }
155
156  dispose() {
157    if (this._disposed) return;
158    this._disposed = true;
159    if (this._objectId) this._context._delegate.releaseHandle(this._objectId).catch(e => {});
160  }
161
162  toString() {
163    return this._preview;
164  }
165
166  _setPreviewCallback(callback) {
167    this._previewCallback = callback;
168  }
169
170  preview() {
171    return this._preview;
172  }
173
174  _setPreview(preview) {
175    this._preview = preview;
176    if (this._previewCallback) this._previewCallback(preview);
177  }
178
179}
180
181exports.JSHandle = JSHandle;
182
183async function evaluate(context, returnByValue, pageFunction, ...args) {
184  return evaluateExpression(context, returnByValue, String(pageFunction), typeof pageFunction === 'function', ...args);
185}
186
187async function evaluateExpression(context, returnByValue, expression, isFunction, ...args) {
188  const utilityScript = await context.utilityScript();
189  expression = normalizeEvaluationExpression(expression, isFunction);
190  const handles = [];
191  const toDispose = [];
192
193  const pushHandle = handle => {
194    handles.push(handle);
195    return handles.length - 1;
196  };
197
198  args = args.map(arg => (0, _utilityScriptSerializers.serializeAsCallArgument)(arg, handle => {
199    if (handle instanceof JSHandle) {
200      if (!handle._objectId) return {
201        fallThrough: handle._value
202      };
203      if (handle._disposed) throw new Error('JSHandle is disposed!');
204      const adopted = context.adoptIfNeeded(handle);
205      if (adopted === null) return {
206        h: pushHandle(Promise.resolve(handle))
207      };
208      toDispose.push(adopted);
209      return {
210        h: pushHandle(adopted)
211      };
212    }
213
214    return {
215      fallThrough: handle
216    };
217  }));
218  const utilityScriptObjectIds = [];
219
220  for (const handle of await Promise.all(handles)) {
221    if (handle._context !== context) throw new Error('JSHandles can be evaluated only in the context they were created!');
222    utilityScriptObjectIds.push(handle._objectId);
223  } // See UtilityScript for arguments.
224
225
226  const utilityScriptValues = [isFunction, returnByValue, expression, args.length, ...args];
227  const script = `(utilityScript, ...args) => utilityScript.evaluate(...args)`;
228
229  try {
230    return await context._delegate.evaluateWithArguments(script, returnByValue, utilityScript, utilityScriptValues, utilityScriptObjectIds);
231  } finally {
232    toDispose.map(handlePromise => handlePromise.then(handle => handle.dispose()));
233  }
234}
235
236async function evaluateExpressionAndWaitForSignals(context, returnByValue, expression, isFunction, ...args) {
237  return await context.waitForSignalsCreatedBy(() => evaluateExpression(context, returnByValue, expression, isFunction, ...args));
238}
239
240function parseUnserializableValue(unserializableValue) {
241  if (unserializableValue === 'NaN') return NaN;
242  if (unserializableValue === 'Infinity') return Infinity;
243  if (unserializableValue === '-Infinity') return -Infinity;
244  if (unserializableValue === '-0') return -0;
245}
246
247function normalizeEvaluationExpression(expression, isFunction) {
248  expression = expression.trim();
249
250  if (isFunction) {
251    try {
252      new Function('(' + expression + ')');
253    } catch (e1) {
254      // This means we might have a function shorthand. Try another
255      // time prefixing 'function '.
256      if (expression.startsWith('async ')) expression = 'async function ' + expression.substring('async '.length);else expression = 'function ' + expression;
257
258      try {
259        new Function('(' + expression + ')');
260      } catch (e2) {
261        // We tried hard to serialize, but there's a weird beast here.
262        throw new Error('Passed function is not well-serializable!');
263      }
264    }
265  }
266
267  if (/^(async)?\s*function(\s|\()/.test(expression)) expression = '(' + expression + ')';
268  return expression;
269} // Error inside the expression evaluation as opposed to a protocol error.
270
271
272class JavaScriptErrorInEvaluate extends Error {}
273
274exports.JavaScriptErrorInEvaluate = JavaScriptErrorInEvaluate;
275
276function isJavaScriptErrorInEvaluate(error) {
277  return error instanceof JavaScriptErrorInEvaluate;
278}
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)