Best JavaScript code snippet using puppeteer
OverridesSupport.js
Source:OverridesSupport.js
1/*2 * Copyright (C) 2012 Google Inc. All rights reserved.3 *4 * Redistribution and use in source and binary forms, with or without5 * modification, are permitted provided that the following conditions are6 * met:7 *8 * * Redistributions of source code must retain the above copyright9 * notice, this list of conditions and the following disclaimer.10 * * Redistributions in binary form must reproduce the above11 * copyright notice, this list of conditions and the following disclaimer12 * in the documentation and/or other materials provided with the13 * distribution.14 * * Neither the name of Google Inc. nor the names of its15 * contributors may be used to endorse or promote products derived from16 * this software without specific prior written permission.17 *18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.29 */30/**31 * @constructor32 * @extends {WebInspector.Object}33 */34WebInspector.OverridesSupport = function()35{36 WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.MainFrameNavigated, this._deviceMetricsChanged.bind(this), this);37 this._deviceMetricsOverrideEnabled = false;38 this._emulateViewportEnabled = false;39 WebInspector.settings.overrideUserAgent.addChangeListener(this._userAgentChanged, this);40 WebInspector.settings.userAgent.addChangeListener(this._userAgentChanged, this);41 WebInspector.settings.overrideDeviceMetrics.addChangeListener(this._deviceMetricsChanged, this);42 WebInspector.settings.deviceMetrics.addChangeListener(this._deviceMetricsChanged, this);43 WebInspector.settings.emulateViewport.addChangeListener(this._deviceMetricsChanged, this);44 WebInspector.settings.deviceFitWindow.addChangeListener(this._deviceMetricsChanged, this);45 WebInspector.settings.overrideGeolocation.addChangeListener(this._geolocationPositionChanged, this);46 WebInspector.settings.geolocationOverride.addChangeListener(this._geolocationPositionChanged, this);47 WebInspector.settings.overrideDeviceOrientation.addChangeListener(this._deviceOrientationChanged, this);48 WebInspector.settings.deviceOrientationOverride.addChangeListener(this._deviceOrientationChanged, this);49 WebInspector.settings.emulateTouchEvents.addChangeListener(this._emulateTouchEventsChanged, this);50 WebInspector.settings.overrideCSSMedia.addChangeListener(this._cssMediaChanged, this);51 WebInspector.settings.emulatedCSSMedia.addChangeListener(this._cssMediaChanged, this);52}53WebInspector.OverridesSupport.Events = {54 OverridesWarningUpdated: "OverridesWarningUpdated",55}56/**57 * @constructor58 * @param {number} width59 * @param {number} height60 * @param {number} deviceScaleFactor61 * @param {boolean} textAutosizing62 */63WebInspector.OverridesSupport.DeviceMetrics = function(width, height, deviceScaleFactor, textAutosizing)64{65 this.width = width;66 this.height = height;67 this.deviceScaleFactor = deviceScaleFactor;68 this.textAutosizing = textAutosizing;69}70/**71 * @return {!WebInspector.OverridesSupport.DeviceMetrics}72 */73WebInspector.OverridesSupport.DeviceMetrics.parseSetting = function(value)74{75 var width = 0;76 var height = 0;77 var deviceScaleFactor = 1;78 var textAutosizing = true;79 if (value) {80 var splitMetrics = value.split("x");81 if (splitMetrics.length >= 3) {82 width = parseInt(splitMetrics[0], 10);83 height = parseInt(splitMetrics[1], 10);84 deviceScaleFactor = parseFloat(splitMetrics[2]);85 if (splitMetrics.length == 4)86 textAutosizing = splitMetrics[3] == 1;87 }88 }89 return new WebInspector.OverridesSupport.DeviceMetrics(width, height, deviceScaleFactor, textAutosizing);90}91/**92 * @return {?WebInspector.OverridesSupport.DeviceMetrics}93 */94WebInspector.OverridesSupport.DeviceMetrics.parseUserInput = function(widthString, heightString, deviceScaleFactorString, textAutosizing)95{96 function isUserInputValid(value, isInteger)97 {98 if (!value)99 return true;100 return isInteger ? /^[0]*[1-9][\d]*$/.test(value) : /^[0]*([1-9][\d]*(\.\d+)?|\.\d+)$/.test(value);101 }102 if (!widthString ^ !heightString)103 return null;104 var isWidthValid = isUserInputValid(widthString, true);105 var isHeightValid = isUserInputValid(heightString, true);106 var isDeviceScaleFactorValid = isUserInputValid(deviceScaleFactorString, false);107 if (!isWidthValid && !isHeightValid && !isDeviceScaleFactorValid)108 return null;109 var width = isWidthValid ? parseInt(widthString || "0", 10) : -1;110 var height = isHeightValid ? parseInt(heightString || "0", 10) : -1;111 var deviceScaleFactor = isDeviceScaleFactorValid ? parseFloat(deviceScaleFactorString) : -1;112 return new WebInspector.OverridesSupport.DeviceMetrics(width, height, deviceScaleFactor, textAutosizing);113}114WebInspector.OverridesSupport.DeviceMetrics.prototype = {115 /**116 * @return {boolean}117 */118 isValid: function()119 {120 return this.isWidthValid() && this.isHeightValid() && this.isDeviceScaleFactorValid();121 },122 /**123 * @return {boolean}124 */125 isWidthValid: function()126 {127 return this.width >= 0;128 },129 /**130 * @return {boolean}131 */132 isHeightValid: function()133 {134 return this.height >= 0;135 },136 /**137 * @return {boolean}138 */139 isDeviceScaleFactorValid: function()140 {141 return this.deviceScaleFactor > 0;142 },143 /**144 * @return {string}145 */146 toSetting: function()147 {148 if (!this.isValid())149 return "";150 return this.width && this.height ? this.width + "x" + this.height + "x" + this.deviceScaleFactor + "x" + (this.textAutosizing ? "1" : "0") : "";151 },152 /**153 * @return {string}154 */155 widthToInput: function()156 {157 return this.isWidthValid() && this.width ? String(this.width) : "";158 },159 /**160 * @return {string}161 */162 heightToInput: function()163 {164 return this.isHeightValid() && this.height ? String(this.height) : "";165 },166 /**167 * @return {string}168 */169 deviceScaleFactorToInput: function()170 {171 return this.isDeviceScaleFactorValid() && this.deviceScaleFactor ? String(this.deviceScaleFactor) : "";172 },173 /**174 * Compute the font scale factor.175 *176 * Chromium on Android uses a device scale adjustment for fonts used in text autosizing for177 * improved legibility. This function computes this adjusted value for text autosizing.178 *179 * For a description of the Android device scale adjustment algorithm, see:180 * chrome/browser/chrome_content_browser_client.cc, GetFontScaleMultiplier(...)181 *182 * @return {number} font scale factor.183 */184 fontScaleFactor: function()185 {186 if (this.isValid()) {187 var minWidth = Math.min(this.width, this.height) / this.deviceScaleFactor;188 var kMinFSM = 1.05;189 var kWidthForMinFSM = 320;190 var kMaxFSM = 1.3;191 var kWidthForMaxFSM = 800;192 if (minWidth <= kWidthForMinFSM)193 return kMinFSM;194 if (minWidth >= kWidthForMaxFSM)195 return kMaxFSM;196 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.197 var ratio = (minWidth - kWidthForMinFSM) / (kWidthForMaxFSM - kWidthForMinFSM);198 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;199 }200 return 1;201 }202}203/**204 * @constructor205 * @param {number} latitude206 * @param {number} longitude207 */208WebInspector.OverridesSupport.GeolocationPosition = function(latitude, longitude, error)209{210 this.latitude = latitude;211 this.longitude = longitude;212 this.error = error;213}214WebInspector.OverridesSupport.GeolocationPosition.prototype = {215 /**216 * @return {string}217 */218 toSetting: function()219 {220 return (typeof this.latitude === "number" && typeof this.longitude === "number" && typeof this.error === "string") ? this.latitude + "@" + this.longitude + ":" + this.error : "";221 }222}223/**224 * @return {!WebInspector.OverridesSupport.GeolocationPosition}225 */226WebInspector.OverridesSupport.GeolocationPosition.parseSetting = function(value)227{228 if (value) {229 var splitError = value.split(":");230 if (splitError.length === 2) {231 var splitPosition = splitError[0].split("@")232 if (splitPosition.length === 2)233 return new WebInspector.OverridesSupport.GeolocationPosition(parseFloat(splitPosition[0]), parseFloat(splitPosition[1]), splitError[1]);234 }235 }236 return new WebInspector.OverridesSupport.GeolocationPosition(0, 0, "");237}238/**239 * @return {?WebInspector.OverridesSupport.GeolocationPosition}240 */241WebInspector.OverridesSupport.GeolocationPosition.parseUserInput = function(latitudeString, longitudeString, errorStatus)242{243 function isUserInputValid(value)244 {245 if (!value)246 return true;247 return /^[-]?[0-9]*[.]?[0-9]*$/.test(value);248 }249 if (!latitudeString ^ !latitudeString)250 return null;251 var isLatitudeValid = isUserInputValid(latitudeString);252 var isLongitudeValid = isUserInputValid(longitudeString);253 if (!isLatitudeValid && !isLongitudeValid)254 return null;255 var latitude = isLatitudeValid ? parseFloat(latitudeString) : -1;256 var longitude = isLongitudeValid ? parseFloat(longitudeString) : -1;257 return new WebInspector.OverridesSupport.GeolocationPosition(latitude, longitude, errorStatus ? "PositionUnavailable" : "");258}259WebInspector.OverridesSupport.GeolocationPosition.clearGeolocationOverride = function()260{261 PageAgent.clearGeolocationOverride();262}263/**264 * @constructor265 * @param {number} alpha266 * @param {number} beta267 * @param {number} gamma268 */269WebInspector.OverridesSupport.DeviceOrientation = function(alpha, beta, gamma)270{271 this.alpha = alpha;272 this.beta = beta;273 this.gamma = gamma;274}275WebInspector.OverridesSupport.DeviceOrientation.prototype = {276 /**277 * @return {string}278 */279 toSetting: function()280 {281 return JSON.stringify(this);282 }283}284/**285 * @return {!WebInspector.OverridesSupport.DeviceOrientation}286 */287WebInspector.OverridesSupport.DeviceOrientation.parseSetting = function(value)288{289 if (value) {290 var jsonObject = JSON.parse(value);291 return new WebInspector.OverridesSupport.DeviceOrientation(jsonObject.alpha, jsonObject.beta, jsonObject.gamma);292 }293 return new WebInspector.OverridesSupport.DeviceOrientation(0, 0, 0);294}295/**296 * @return {?WebInspector.OverridesSupport.DeviceOrientation}297 */298WebInspector.OverridesSupport.DeviceOrientation.parseUserInput = function(alphaString, betaString, gammaString)299{300 function isUserInputValid(value)301 {302 if (!value)303 return true;304 return /^[-]?[0-9]*[.]?[0-9]*$/.test(value);305 }306 if (!alphaString ^ !betaString ^ !gammaString)307 return null;308 var isAlphaValid = isUserInputValid(alphaString);309 var isBetaValid = isUserInputValid(betaString);310 var isGammaValid = isUserInputValid(gammaString);311 if (!isAlphaValid && !isBetaValid && !isGammaValid)312 return null;313 var alpha = isAlphaValid ? parseFloat(alphaString) : -1;314 var beta = isBetaValid ? parseFloat(betaString) : -1;315 var gamma = isGammaValid ? parseFloat(gammaString) : -1;316 return new WebInspector.OverridesSupport.DeviceOrientation(alpha, beta, gamma);317}318WebInspector.OverridesSupport.DeviceOrientation.clearDeviceOrientationOverride = function()319{320 PageAgent.clearDeviceOrientationOverride();321}322WebInspector.OverridesSupport.prototype = {323 /**324 * @param {string} deviceMetrics325 * @param {string} userAgent326 */327 emulateDevice: function(deviceMetrics, userAgent)328 {329 this._deviceMetricsChangedListenerMuted = true;330 WebInspector.settings.deviceMetrics.set(deviceMetrics);331 WebInspector.settings.userAgent.set(userAgent);332 WebInspector.settings.overrideDeviceMetrics.set(true);333 WebInspector.settings.overrideUserAgent.set(true);334 WebInspector.settings.emulateTouchEvents.set(true);335 WebInspector.settings.emulateViewport.set(true);336 delete this._deviceMetricsChangedListenerMuted;337 this._deviceMetricsChanged();338 },339 reset: function()340 {341 this._deviceMetricsChangedListenerMuted = true;342 WebInspector.settings.overrideDeviceMetrics.set(false);343 WebInspector.settings.overrideUserAgent.set(false);344 WebInspector.settings.emulateTouchEvents.set(false);345 WebInspector.settings.overrideDeviceOrientation.set(false);346 WebInspector.settings.overrideGeolocation.set(false);347 WebInspector.settings.overrideCSSMedia.set(false);348 WebInspector.settings.emulateViewport.set(false);349 WebInspector.settings.deviceMetrics.set("");350 delete this._deviceMetricsChangedListenerMuted;351 this._deviceMetricsChanged();352 },353 applyInitialOverrides: function()354 {355 this._deviceMetricsChangedListenerMuted = true;356 this._userAgentChanged();357 this._deviceMetricsChanged();358 this._deviceOrientationChanged();359 this._geolocationPositionChanged();360 this._emulateTouchEventsChanged();361 this._cssMediaChanged();362 delete this._deviceMetricsChangedListenerMuted;363 this._deviceMetricsChanged();364 this._revealOverridesTabIfNeeded();365 },366 _userAgentChanged: function()367 {368 if (WebInspector.isInspectingDevice())369 return;370 NetworkAgent.setUserAgentOverride(WebInspector.settings.overrideUserAgent.get() ? WebInspector.settings.userAgent.get() : "");371 },372 _deviceMetricsChanged: function()373 {374 if (this._deviceMetricsChangedListenerMuted)375 return;376 var metrics = WebInspector.OverridesSupport.DeviceMetrics.parseSetting(WebInspector.settings.overrideDeviceMetrics.get() ? WebInspector.settings.deviceMetrics.get() : "");377 if (!metrics.isValid())378 return;379 var dipWidth = Math.round(metrics.width / metrics.deviceScaleFactor);380 var dipHeight = Math.round(metrics.height / metrics.deviceScaleFactor);381 // Disable override without checks.382 if (dipWidth && dipHeight && WebInspector.isInspectingDevice()) {383 this._updateWarningMessage(WebInspector.UIString("Screen emulation on the device is not available."));384 return;385 }386 PageAgent.setDeviceMetricsOverride(dipWidth, dipHeight, metrics.deviceScaleFactor, WebInspector.settings.emulateViewport.get(), WebInspector.settings.deviceFitWindow.get(), metrics.textAutosizing, metrics.fontScaleFactor(), apiCallback.bind(this));387 /**388 * @param {?Protocol.Error} error389 * @this {WebInspector.OverridesSupport}390 */391 function apiCallback(error)392 {393 if (error) {394 this._updateWarningMessage(WebInspector.UIString("Screen emulation is not available on this page."));395 return;396 }397 var metricsOverrideEnabled = !!(dipWidth && dipHeight);398 var viewportEnabled = WebInspector.settings.emulateViewport.get();399 this._updateWarningMessage(this._deviceMetricsOverrideEnabled !== metricsOverrideEnabled || (metricsOverrideEnabled && this._emulateViewportEnabled != viewportEnabled) ?400 WebInspector.UIString("You might need to reload the page for proper user agent spoofing and viewport rendering.") : "");401 this._deviceMetricsOverrideEnabled = metricsOverrideEnabled;402 this._emulateViewportEnabled = viewportEnabled;403 }404 },405 _geolocationPositionChanged: function()406 {407 if (!WebInspector.settings.overrideGeolocation.get()) {408 PageAgent.clearGeolocationOverride();409 return;410 }411 var geolocation = WebInspector.OverridesSupport.GeolocationPosition.parseSetting(WebInspector.settings.geolocationOverride.get());412 if (geolocation.error)413 PageAgent.setGeolocationOverride();414 else415 PageAgent.setGeolocationOverride(geolocation.latitude, geolocation.longitude, 150);416 },417 _deviceOrientationChanged: function()418 {419 if (!WebInspector.settings.overrideDeviceOrientation.get()) {420 PageAgent.clearDeviceOrientationOverride();421 return;422 }423 if (WebInspector.isInspectingDevice())424 return;425 var deviceOrientation = WebInspector.OverridesSupport.DeviceOrientation.parseSetting(WebInspector.settings.deviceOrientationOverride.get());426 PageAgent.setDeviceOrientationOverride(deviceOrientation.alpha, deviceOrientation.beta, deviceOrientation.gamma);427 },428 _emulateTouchEventsChanged: function()429 {430 if (WebInspector.isInspectingDevice() && WebInspector.settings.emulateTouchEvents.get())431 return;432 WebInspector.domAgent.emulateTouchEventObjects(WebInspector.settings.emulateTouchEvents.get());433 },434 _cssMediaChanged: function()435 {436 PageAgent.setEmulatedMedia(WebInspector.settings.overrideCSSMedia.get() ? WebInspector.settings.emulatedCSSMedia.get() : "");437 WebInspector.cssModel.mediaQueryResultChanged();438 },439 _anyOverrideIsEnabled: function()440 {441 return WebInspector.settings.overrideUserAgent.get() || WebInspector.settings.overrideDeviceMetrics.get() ||442 WebInspector.settings.overrideGeolocation.get() || WebInspector.settings.overrideDeviceOrientation.get() ||443 WebInspector.settings.emulateTouchEvents.get() || WebInspector.settings.overrideCSSMedia.get();444 },445 _revealOverridesTabIfNeeded: function()446 {447 if (this._anyOverrideIsEnabled()) {448 if (!WebInspector.settings.showEmulationViewInDrawer.get())449 WebInspector.settings.showEmulationViewInDrawer.set(true);450 WebInspector.inspectorView.showViewInDrawer("emulation");451 }452 },453 /**454 * @param {string} warningMessage455 */456 _updateWarningMessage: function(warningMessage)457 {458 this._warningMessage = warningMessage;459 this.dispatchEventToListeners(WebInspector.OverridesSupport.Events.OverridesWarningUpdated);460 },461 /**462 * @return {string}463 */464 warningMessage: function()465 {466 return this._warningMessage || "";467 },468 __proto__: WebInspector.Object.prototype469}470/**471 * @type {!WebInspector.OverridesSupport}472 */...
index.js
Source:index.js
1var Chrome = require('chrome-remote-interface')2var prettyBytes = require('pretty-bytes')3var evaluate = require('./helpers/evaluate.js')4var Plan = require('./helpers/plan')5var find = require('./helpers/find')6function Run(opts) {7 this.opts = opts8 this.p = new Plan(4)9 this.stats = {}10 this.stats.requests = []11 this.stats.network = {}12 this.stats.network.total = 013 this.stats.network.typesUsage = {14 "Document": { count: 0, weight: 0},15 "Fetch": { count: 0, weight: 0},16 "Font": { count: 0, weight: 0},17 "Image": { count: 0, weight: 0},18 "Other": { count: 0, weight: 0},19 "Script": { count: 0, weight: 0},20 "Stylesheet": { count: 0, weight: 0},21 "WebSocket": { count: 0, weight: 0},22 "XHR": { count: 0, weight: 0}23 }24 this.stats.unused = {}25 // Find unused elements26 this.p.on("done::els", this._onElsDone.bind(this))27 // Count types usage and total page weight28 this.p.on('done::requests', this._onRequestsDone.bind(this))29 // all done30 this.p.on('done', this._onDone.bind(this))31}32Run.prototype.init = function() {33 var self = this34 Chrome(function (chrome) {35 self.chrome = chrome36 evaluate.setChrome(chrome)37 self.chrome.Page.enable()38 self.emulate()39 })40}41Run.prototype.emulate = function() {42 this.chrome.send('Page.setDeviceMetricsOverride', {43 mobile: this.opts.mobile,44 width: parseInt(this.opts.width),45 height: parseInt(this.opts.height),46 emulateViewport: this.opts.emulateViewport || true,47 fitWindow: true,48 deviceScaleFactor: parseInt(this.opts.deviceScaleFactor),49 scale: parseInt(this.opts.scale)50 }, this._handleEmulate.bind(this))51}52Run.prototype._handleEmulate = function(err) {53 if ( err ) {54 this.chrome.close()55 return this.opts.cb(new Error("Issue in emulate"))56 }57 var self = this58 this.chrome.Network.enable()59 if ( !this.opts.userAgent ) {60 this.chrome.Page.navigate({'url': this.opts.link})61 // Collect requests62 this.collectReqs()63 } else {64 this.setUa()65 }66 this._handleOnload()67}68Run.prototype.setUa = function() {69 var self = this70 this.chrome.send('Network.setUserAgentOverride', {71 'userAgent': this.opts.userAgent72 }, function(err) {73 if ( err ) {74 self.chrome.close()75 return self.opts.cb(new Error("Issue in overriding user-agent"))76 }77 self.chrome.Page.navigate({'url': self.opts.link})78 // Collect requests79 self.collectReqs()80 })81}82Run.prototype.collectReqs = function() {83 var self = this84 this.chrome.on('Network.responseReceived', function (req) {85 if ( req.response.url.substr(0, 6) == "chrome" ) return86 var contentLength = parseInt(req.response.headers['Content-Length']) || 087 self.stats.requests.push(88 {89 url: req.response.url,90 type: req.type,91 contentLength: contentLength,92 humanWeight: prettyBytes(contentLength)93 }94 )95 })96}97Run.prototype._handleOnload = function() {98 var self = this99 this.chrome.on('Page.loadEventFired', function() {100 self.chrome.Runtime.enable()101 self.p.done('requests', self.stats.requests)102 // Collect unused elements103 evaluate.eval(__dirname + '/unusedElements.js', function(err, data) {104 if ( err ) {105 self.chrome.close()106 return self.opts.cb(new Error("Issue in finding unused elements."))107 }108 self.stats.unused.elements = JSON.parse(data.result.value)109 self.p.done("els", self.stats.unused.elements)110 })111 })112}113Run.prototype._onElsDone = function() {114 this.stats.unused.bytes = { total: 0, list: [] }115 var bytes = this.stats.unused.bytes116 var unusedEls = this.stats.unused.elements117 for (var i = 0; i < unusedEls.length; i++) {118 obj = find(unusedEls[i].images, this.stats.requests, "url")119 if ( obj ) {120 bytes.list.push(obj)121 bytes.total += parseInt(obj.contentLength)122 obj.humanWeight = prettyBytes(parseInt(obj.contentLength))123 }124 }125 bytes.humanWeight = prettyBytes(bytes.total)126 this.p.done()127}128Run.prototype._onRequestsDone = function(requests) {129 // aggregate network stats!130 for (var i = 0; i < requests.length; i++) {131 if ( requests[i].contentLength ) {132 this.stats.network.total += parseInt(requests[i].contentLength)133 this.stats.network.typesUsage[requests[i].type].weight += parseInt(requests[i].contentLength)134 }135 this.stats.network.typesUsage[requests[i].type].count++136 }137 this.stats.network.humanTotal = prettyBytes(this.stats.network.total)138 139 for (var k in this.stats.network.typesUsage) {140 var type = this.stats.network.typesUsage[k]141 type.humanWeight = prettyBytes(type.weight)142 }143 144 this.p.done()145}146Run.prototype._onDone = function() {147 this.chrome.close()148 this.opts.cb(false, this.stats)149}...
tasks.js
Source:tasks.js
1import Pdf from "../components/taskModule/Pdf.vue";2import Click from "../components/taskModule/Click.vue";3import Sleep from "../components/taskModule/Sleep.vue";4import Evaluate from "../components/taskModule/Evaluate.vue";5import Navigate from "../components/taskModule/Navigate.vue";6import SetValue from "../components/taskModule/SetValue.vue";7import Screenshot from "../components/taskModule/Screenshot.vue";8import AddCookies from "../components/taskModule/AddCookies.vue";9import WaitVisible from "../components/taskModule/WaitVisible.vue";10import AddReqHeaders from "../components/taskModule/AddReqHeaders.vue";11import EmulateViewport from "../components/taskModule/EmulateViewport.vue";12import CaptureScreenshot from "../components/taskModule/CaptureScreenshot.vue";13import UnderDevelopment from "../components/taskModule/UnderDevelopment.vue";14export default [15 {16 name: "pdf",17 title: "çæPDF",18 argsModule: Pdf19 },20 {21 name: "click",22 title: "ç¹å»å
ç´ ",23 argsModule: Click24 },25 {26 name: "sleep",27 title: "çå¾
ä¸ä¼",28 argsModule: Sleep29 },30 {31 name: "evaluate",32 title: "æ§è¡èæ¬",33 argsModule: Evaluate34 },35 {36 name: "navigate",37 title: "æå¼ç½å",38 argsModule: Navigate39 },40 {41 name: "setValue",42 title: "å¾è¾å
¥æ¡è¾å
¥å
容",43 argsModule: SetValue44 },45 {46 name: "screenshot",47 title: "æªåç½é¡µå
容",48 argsModule: Screenshot49 },50 {51 name: "addCookies",52 title: "æ·»å Cookies",53 argsModule: AddCookies54 },55 {56 name: "waitVisible",57 title: "çå¾
å
ç´ å è½½å®æ",58 argsModule: WaitVisible59 },60 {61 name: "addReqHeaders",62 title: "æ·»å 请æ±å¤´",63 argsModule: AddReqHeaders64 },65 {66 name: "emulateViewport",67 title: "æ¹åçªå£å¤§å°",68 argsModule: EmulateViewport69 },70 {71 name: "captureScreenshot",72 title: "æè·å±å¹",73 argsModule: CaptureScreenshot74 },75 {76 name: "collectDataByExcel",77 title: "éè¿è¡¨æ ¼æéæ°æ®",78 argsModule: UnderDevelopment79 },80 {81 name: "collectDataByWord",82 title: "éè¿ææ¡£æéæ°æ®",83 argsModule: UnderDevelopment84 },85 {86 name: "packageFile",87 title: "æå
ç®åçæçæææ件",88 argsModule: UnderDevelopment89 }...
EmulationManager.js
Source:EmulationManager.js
...6 this._emulatingMobile = false;7 this._hasTouch = false;8 this._client = client;9 }10 async emulateViewport(viewport) {11 const mobile = viewport.isMobile || false;12 const width = viewport.width;13 const height = viewport.height;14 const deviceScaleFactor = viewport.deviceScaleFactor || 1;15 const screenOrientation = viewport.isLandscape16 ? { angle: 90, type: 'landscapePrimary' }17 : { angle: 0, type: 'portraitPrimary' };18 const hasTouch = viewport.hasTouch || false;19 await Promise.all([20 this._client.send('Emulation.setDeviceMetricsOverride', {21 mobile,22 width,23 height,24 deviceScaleFactor,...
responsive.js
Source:responsive.js
1var Rwdperf = require('rwdperf');2new Rwdperf({3 link: "http://google.com",4 mobile: true,5 emulateViewport: true,6 deviceScaleFactor: 1,7 scale: 1,8 width: 400,9 height: 500,10 userAgent: null,11 cb: handler12}).init();13function handler(err, data) {14 if ( err ) return console.log(err);15 // all worked out! do amazing stuff with the data...16 console.log(JSON.stringify(data));...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!