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

fetch_devices.js

Source: fetch_devices.js Github

copy
1#!/usr/bin/env node
2/**
3 * Copyright 2017 Google Inc. All rights reserved.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18const util = require('util');
19const fs = require('fs');
20const path = require('path');
21const DEVICES_URL = 'https://raw.githubusercontent.com/ChromeDevTools/devtools-frontend/master/front_end/emulated_devices/module.json';
22
23const template = `/**
24 * Copyright 2017 Google Inc. All rights reserved.
25 *
26 * Licensed under the Apache License, Version 2.0 (the "License");
27 * you may not use this file except in compliance with the License.
28 * You may obtain a copy of the License at
29 *
30 *     http://www.apache.org/licenses/LICENSE-2.0
31 *
32 * Unless required by applicable law or agreed to in writing, software
33 * distributed under the License is distributed on an "AS IS" BASIS,
34 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35 * See the License for the specific language governing permissions and
36 * limitations under the License.
37 */
38
39module.exports = %s;
40for (let device of module.exports)
41  module.exports[device.name] = device;
42`;
43
44const help = `Usage:  node ${path.basename(__filename)} [-u <from>] <outputPath>
45  -u, --url    The URL to load devices descriptor from. If not set,
46               devices will be fetched from the tip-of-tree of DevTools
47               frontend.
48
49  -h, --help   Show this help message
50
51Fetch Chrome DevTools front-end emulation devices from given URL, convert them to puppeteer
52devices and save to the <outputPath>.
53`;
54
55const argv = require('minimist')(process.argv.slice(2), {
56  alias: { u: 'url', h: 'help' },
57});
58
59if (argv.help) {
60  console.log(help);
61  return;
62}
63
64const url = argv.url || DEVICES_URL;
65const outputPath = argv._[0];
66if (!outputPath) {
67  console.log('ERROR: output file name is missing. Use --help for help.');
68  return;
69}
70
71main(url);
72
73async function main(url) {
74  console.log('GET ' + url);
75  const text = await httpGET(url);
76  let json = null;
77  try {
78    json = JSON.parse(text);
79  } catch (e) {
80    console.error(`FAILED: error parsing response - ${e.message}`);
81    return;
82  }
83  const devicePayloads = json.extensions.filter(extension => extension.type === 'emulated-device').map(extension => extension.device);
84  let devices = [];
85  for (const payload of devicePayloads) {
86    const device = createDevice(payload, false);
87    const landscape = createDevice(payload, true);
88    devices.push(device);
89    if (landscape.viewport.width !== device.viewport.width || landscape.viewport.height !== device.viewport.height)
90      devices.push(landscape);
91  }
92  devices = devices.filter(device => device.viewport.isMobile);
93  devices.sort((a, b) => a.name.localeCompare(b.name));
94  // Use single-quotes instead of double-quotes to conform with codestyle.
95  const serialized = JSON.stringify(devices, null, 2)
96      .replace(/'/g, `\\'`)
97      .replace(/"/g, `'`);
98  const result = util.format(template, serialized);
99  fs.writeFileSync(outputPath, result, 'utf8');
100}
101
102/**
103 * @param {*} descriptor
104 * @param {boolean} landscape
105 * @return {!Object}
106 */
107function createDevice(descriptor, landscape) {
108  const devicePayload = loadFromJSONV1(descriptor);
109  const viewportPayload = landscape ? devicePayload.horizontal : devicePayload.vertical;
110  return {
111    name: descriptor.title + (landscape ? ' landscape' : ''),
112    userAgent: devicePayload.userAgent,
113    viewport: {
114      width: viewportPayload.width,
115      height: viewportPayload.height,
116      deviceScaleFactor: devicePayload.deviceScaleFactor,
117      isMobile: devicePayload.capabilities.includes('mobile'),
118      hasTouch: devicePayload.capabilities.includes('touch'),
119      isLandscape: landscape || false
120    }
121  };
122}
123
124/**
125 * @param {*} json
126 * @return {?Object}
127 */
128function loadFromJSONV1(json) {
129  /**
130   * @param {*} object
131   * @param {string} key
132   * @param {string} type
133   * @param {*=} defaultValue
134   * @return {*}
135   */
136  function parseValue(object, key, type, defaultValue) {
137    if (typeof object !== 'object' || object === null || !object.hasOwnProperty(key)) {
138      if (typeof defaultValue !== 'undefined')
139        return defaultValue;
140      throw new Error('Emulated device is missing required property \'' + key + '\'');
141    }
142    const value = object[key];
143    if (typeof value !== type || value === null)
144      throw new Error('Emulated device property \'' + key + '\' has wrong type \'' + typeof value + '\'');
145    return value;
146  }
147
148  /**
149   * @param {*} object
150   * @param {string} key
151   * @return {number}
152   */
153  function parseIntValue(object, key) {
154    const value = /** @type {number} */ (parseValue(object, key, 'number'));
155    if (value !== Math.abs(value))
156      throw new Error('Emulated device value \'' + key + '\' must be integer');
157    return value;
158  }
159
160  /**
161   * @param {*} json
162   * @return {!{width: number, height: number}}
163   */
164  function parseOrientation(json) {
165    const result = {};
166    const minDeviceSize = 50;
167    const maxDeviceSize = 9999;
168    result.width = parseIntValue(json, 'width');
169    if (result.width < 0 || result.width > maxDeviceSize ||
170        result.width < minDeviceSize)
171      throw new Error('Emulated device has wrong width: ' + result.width);
172
173    result.height = parseIntValue(json, 'height');
174    if (result.height < 0 || result.height > maxDeviceSize ||
175        result.height < minDeviceSize)
176      throw new Error('Emulated device has wrong height: ' + result.height);
177
178    return /** @type {!{width: number, height: number}} */ (result);
179  }
180
181  const result = {};
182  result.type = /** @type {string} */ (parseValue(json, 'type', 'string'));
183  result.userAgent = /** @type {string} */ (parseValue(json, 'user-agent', 'string'));
184
185  const capabilities = parseValue(json, 'capabilities', 'object', []);
186  if (!Array.isArray(capabilities))
187    throw new Error('Emulated device capabilities must be an array');
188  result.capabilities = [];
189  for (let i = 0; i < capabilities.length; ++i) {
190    if (typeof capabilities[i] !== 'string')
191      throw new Error('Emulated device capability must be a string');
192    result.capabilities.push(capabilities[i]);
193  }
194
195  result.deviceScaleFactor = /** @type {number} */ (parseValue(json['screen'], 'device-pixel-ratio', 'number'));
196  if (result.deviceScaleFactor < 0 || result.deviceScaleFactor > 100)
197    throw new Error('Emulated device has wrong deviceScaleFactor: ' + result.deviceScaleFactor);
198
199  result.vertical = parseOrientation(parseValue(json['screen'], 'vertical', 'object'));
200  result.horizontal = parseOrientation(parseValue(json['screen'], 'horizontal', 'object'));
201  return result;
202}
203
204/**
205 * @param {url}
206 * @return {!Promise}
207 */
208function httpGET(url) {
209  let fulfill, reject;
210  const promise = new Promise((res, rej) => {
211    fulfill = res;
212    reject = rej;
213  });
214  const driver = url.startsWith('https://') ? require('https') : require('http');
215  const request = driver.get(url, response => {
216    let data = '';
217    response.setEncoding('utf8');
218    response.on('data', chunk => data += chunk);
219    response.on('end', () => fulfill(data));
220    response.on('error', reject);
221  });
222  request.on('error', reject);
223  return promise;
224}
225
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)