How to use serializeArgument method in Puppeteer

Best JavaScript code snippet using puppeteer

Run Puppeteer automation tests on LambdaTest cloud grid

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

serializer.cjs

Source: serializer.cjs Github

copy
1const {digg} = require("diggerize")
2
3module.exports = class Serializer {
4  static serialize (arg) {
5    const serialize = new Serializer(arg)
6
7    return serialize.serialize()
8  }
9
10  constructor (arg) {
11    this.arg = arg
12  }
13
14  serialize () {
15    return this.serializeArgument(this.arg)
16  }
17
18  serializeArgument (arg) {
19    if (typeof arg == "object" && arg.constructor.apiMakerType == "BaseModel") {
20      return {
21        api_maker_type: "model",
22        model_class_name: digg(arg.modelClassData(), "name"),
23        model_id: arg.id()
24      }
25    } else if (typeof arg == "function" && arg.apiMakerType == "BaseModel") {
26      return {
27        api_maker_type: "resource",
28        name: digg(arg.modelClassData(), "name")
29      }
30    } else if (arg instanceof Date) {
31      let offsetNumber = parseInt((arg.getTimezoneOffset() / 60) * 100, 10)
32
33      offsetNumber = -offsetNumber
34
35      let offset = `${offsetNumber}`
36
37      while (offset.length < 4) {
38        offset = `0${offset}`
39      }
40
41      return {
42        api_maker_type: "datetime",
43        value: `${arg.getFullYear()}-${arg.getMonth() + 1}-${arg.getDate()} ${arg.getHours()}:${arg.getMinutes()}:${arg.getSeconds()}+${offset}`
44      }
45    } else if (Array.isArray(arg)) {
46      return this.serializeArray(arg)
47    } else if (typeof arg == "object" && arg.constructor && arg.constructor.apiMakerType == "Collection") {
48      return {
49        api_maker_type: "collection",
50        value: this.serializeObject(arg)
51      }
52    } else if (typeof arg == "object" && arg !== null && arg.constructor.name == "Object") {
53      return this.serializeObject(arg)
54    } else {
55      return arg
56    }
57  }
58
59  serializeArray (arg) {
60    return arg.map((value) => this.serializeArgument(value))
61  }
62
63  serializeObject (arg) {
64    const newObject = {}
65
66    for (const key in arg) {
67      const value = arg[key]
68      const newValue = this.serializeArgument(value)
69      const newKey = this.serializeArgument(key)
70
71      newObject[newKey] = newValue
72    }
73
74    return newObject
75  }
76}
77
Full Screen

helpers.js

Source: helpers.js Github

copy
1var P = require('p-promise'),
2    _ = require('lodash');
3
4exports.waitFor = function waitFor(milliseconds)
5{
6    var deferred = P.defer();
7    setTimeout(deferred.resolve, milliseconds);
8    return deferred.promise;
9};
10
11exports.serializeArgument = function serializeArgument(argument)
12{
13    var value = String(argument),
14        length = Buffer.byteLength(value);
15
16    return '$' + length + '\r\n' + value + '\r\n';
17};
18
19exports.decodeBuffers = function decodeBuffers(reply)
20{
21    if (Buffer.isBuffer(reply))
22        return String(reply);
23
24    if (Array.isArray(reply))
25        return _.map(reply, decodeBuffers);
26
27    return reply;
28};
29
30exports.rejectQueueWith = function rejectQueueWith(queue, message)
31{
32    while (queue.length)
33    {
34        var command = queue.shift();
35        command.isQueued = command.beginsQueue = command.endsQueue = command.discardsQueue = false;
36        command.rejectWith(message);
37    }
38};
39
Full Screen

jsHandle.js

Source: jsHandle.js Github

copy
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4  value: true
5});
6exports.serializeArgument = serializeArgument;
7exports.parseResult = parseResult;
8exports.assertMaxArguments = assertMaxArguments;
9exports.JSHandle = void 0;
10
11var _channelOwner = require("./channelOwner");
12
13var _serializers = require("../protocol/serializers");
14
15/**
16 * Copyright (c) Microsoft Corporation.
17 *
18 * Licensed under the Apache License, Version 2.0 (the "License");
19 * you may not use this file except in compliance with the License.
20 * You may obtain a copy of the License at
21 *
22 * http://www.apache.org/licenses/LICENSE-2.0
23 *
24 * Unless required by applicable law or agreed to in writing, software
25 * distributed under the License is distributed on an "AS IS" BASIS,
26 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
27 * See the License for the specific language governing permissions and
28 * limitations under the License.
29 */
30class JSHandle extends _channelOwner.ChannelOwner {
31  static from(handle) {
32    return handle._object;
33  }
34
35  constructor(parent, type, guid, initializer) {
36    super(parent, type, guid, initializer);
37    this._preview = void 0;
38    this._preview = this._initializer.preview;
39
40    this._channel.on('previewUpdated', ({
41      preview
42    }) => this._preview = preview);
43  }
44
45  async evaluate(pageFunction, arg) {
46    return this._wrapApiCall(async channel => {
47      const result = await channel.evaluateExpression({
48        expression: String(pageFunction),
49        isFunction: typeof pageFunction === 'function',
50        arg: serializeArgument(arg)
51      });
52      return parseResult(result.value);
53    });
54  }
55
56  async evaluateHandle(pageFunction, arg) {
57    return this._wrapApiCall(async channel => {
58      const result = await channel.evaluateExpressionHandle({
59        expression: String(pageFunction),
60        isFunction: typeof pageFunction === 'function',
61        arg: serializeArgument(arg)
62      });
63      return JSHandle.from(result.handle);
64    });
65  }
66
67  async getProperty(propertyName) {
68    return this._wrapApiCall(async channel => {
69      const result = await channel.getProperty({
70        name: propertyName
71      });
72      return JSHandle.from(result.handle);
73    });
74  }
75
76  async getProperties() {
77    return this._wrapApiCall(async channel => {
78      const map = new Map();
79
80      for (const {
81        name,
82        value
83      } of (await channel.getPropertyList()).properties) map.set(name, JSHandle.from(value));
84
85      return map;
86    });
87  }
88
89  async jsonValue() {
90    return this._wrapApiCall(async channel => {
91      return parseResult((await channel.jsonValue()).value);
92    });
93  }
94
95  asElement() {
96    return null;
97  }
98
99  async dispose() {
100    return this._wrapApiCall(async channel => {
101      return await channel.dispose();
102    });
103  }
104
105  toString() {
106    return this._preview;
107  }
108
109} // This function takes care of converting all JSHandles to their channels,
110// so that generic channel serializer converts them to guids.
111
112
113exports.JSHandle = JSHandle;
114
115function serializeArgument(arg) {
116  const handles = [];
117
118  const pushHandle = channel => {
119    handles.push(channel);
120    return handles.length - 1;
121  };
122
123  const value = (0, _serializers.serializeValue)(arg, value => {
124    if (value instanceof JSHandle) return {
125      h: pushHandle(value._channel)
126    };
127    return {
128      fallThrough: value
129    };
130  }, new Set());
131  return {
132    value,
133    handles
134  };
135}
136
137function parseResult(value) {
138  return (0, _serializers.parseSerializedValue)(value, undefined);
139}
140
141function assertMaxArguments(count, max) {
142  if (count > max) throw new Error('Too many arguments. If you need to pass more than 1 argument to the function wrap them in an object.');
143}
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 Puppeteer 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)