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

tasks.js

Source: tasks.js Github

copy
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: Pdf
19  },
20  {
21    name: "click",
22    title: "点击元素",
23    argsModule: Click
24  },
25  {
26    name: "sleep",
27    title: "等待一会",
28    argsModule: Sleep
29  },
30  {
31    name: "evaluate",
32    title: "执行脚本",
33    argsModule: Evaluate
34  },
35  {
36    name: "navigate",
37    title: "打开网址",
38    argsModule: Navigate
39  },
40  {
41    name: "setValue",
42    title: "往输入框输入内容",
43    argsModule: SetValue
44  },
45  {
46    name: "screenshot",
47    title: "截取网页内容",
48    argsModule: Screenshot
49  },
50  {
51    name: "addCookies",
52    title: "添加Cookies",
53    argsModule: AddCookies
54  },
55  {
56    name: "waitVisible",
57    title: "等待元素加载完成",
58    argsModule: WaitVisible
59  },
60  {
61    name: "addReqHeaders",
62    title: "添加请求头",
63    argsModule: AddReqHeaders
64  },
65  {
66    name: "emulateViewport",
67    title: "改变窗口大小",
68    argsModule: EmulateViewport
69  },
70  {
71    name: "captureScreenshot",
72    title: "捕获屏幕",
73    argsModule: CaptureScreenshot
74  },
75  {
76    name: "collectDataByExcel",
77    title: "通过表格搜集数据",
78    argsModule: UnderDevelopment
79  },
80  {
81    name: "collectDataByWord",
82    title: "通过文档搜集数据",
83    argsModule: UnderDevelopment
84  },
85  {
86    name: "packageFile",
87    title: "打包目前生成的所有文件",
88    argsModule: UnderDevelopment
89  }
90];
91
Full Screen

responsive.js

Source: responsive.js Github

copy
1var Rwdperf = require('rwdperf');
2
3new Rwdperf({
4    link: "http://google.com",
5    mobile: true,
6    emulateViewport: true,
7    deviceScaleFactor: 1,
8    scale: 1,
9    width: 400,
10    height: 500,
11    userAgent: null,
12    cb: handler
13}).init();
14
15function handler(err, data) {
16    if ( err ) return console.log(err);
17
18    // all worked out! do amazing stuff with the data...
19    console.log(JSON.stringify(data));
20}
Full Screen

index.js

Source: index.js Github

copy
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')
6
7function Run(opts) {
8  this.opts = opts
9  this.p = new Plan(4)
10  this.stats = {}
11  this.stats.requests = []
12  this.stats.network = {}
13  this.stats.network.total = 0
14  this.stats.network.typesUsage = {
15    "Document": { count: 0, weight: 0},
16    "Fetch": { count: 0, weight: 0},
17    "Font": { count: 0, weight: 0},
18    "Image": { count: 0, weight: 0},
19    "Other": { count: 0, weight: 0},
20    "Script": { count: 0, weight: 0},
21    "Stylesheet": { count: 0, weight: 0},
22    "WebSocket": { count: 0, weight: 0},
23    "XHR": { count: 0, weight: 0}
24  }
25  this.stats.unused = {}
26  // Find unused elements
27  this.p.on("done::els", this._onElsDone.bind(this))
28  // Count types usage and total page weight
29  this.p.on('done::requests', this._onRequestsDone.bind(this))
30  // all done
31  this.p.on('done', this._onDone.bind(this))
32}
33
34Run.prototype.init = function() {
35  var self = this
36  Chrome(function (chrome) {
37    self.chrome = chrome
38    evaluate.setChrome(chrome)
39    self.chrome.Page.enable()
40    self.emulate()
41  })
42}
43
44Run.prototype.emulate = function() {
45  this.chrome.send('Page.setDeviceMetricsOverride', {
46    mobile: this.opts.mobile,
47    width: parseInt(this.opts.width),
48    height: parseInt(this.opts.height),
49    emulateViewport: this.opts.emulateViewport || true,
50    fitWindow: true,
51    deviceScaleFactor: parseInt(this.opts.deviceScaleFactor),
52    scale: parseInt(this.opts.scale)
53  }, this._handleEmulate.bind(this))
54}
55
56Run.prototype._handleEmulate = function(err) {
57  if ( err ) {
58    this.chrome.close()
59    return this.opts.cb(new Error("Issue in emulate"))
60  }
61  var self = this
62  this.chrome.Network.enable()
63  if ( !this.opts.userAgent ) {
64    this.chrome.Page.navigate({'url': this.opts.link})
65    // Collect requests
66    this.collectReqs()
67  } else {
68    this.setUa()
69  }
70  this._handleOnload()
71}
72
73Run.prototype.setUa = function() {
74  var self = this
75  this.chrome.send('Network.setUserAgentOverride', {
76    'userAgent': this.opts.userAgent
77  }, function(err) {
78    if ( err ) {
79      self.chrome.close()
80      return self.opts.cb(new Error("Issue in overriding user-agent"))
81    }
82
83    self.chrome.Page.navigate({'url': self.opts.link})
84    // Collect requests
85    self.collectReqs()
86  })
87}
88
89Run.prototype.collectReqs = function() {
90  var self = this
91  this.chrome.on('Network.responseReceived', function (req) {
92    if ( req.response.url.substr(0, 6) == "chrome" ) return
93      var contentLength = parseInt(req.response.headers['Content-Length']) || 0
94      self.stats.requests.push(
95        {
96          url: req.response.url,
97          type: req.type,
98          contentLength: contentLength,
99          humanWeight: prettyBytes(contentLength)
100        }
101      )
102  })
103}
104
105Run.prototype._handleOnload = function() {
106  var self = this
107  this.chrome.on('Page.loadEventFired', function() {
108    self.chrome.Runtime.enable()
109    self.p.done('requests', self.stats.requests)
110    // Collect unused elements
111    evaluate.eval(__dirname + '/unusedElements.js', function(err, data) {
112      if ( err ) {
113        self.chrome.close()
114        return self.opts.cb(new Error("Issue in finding unused elements."))
115      }
116      self.stats.unused.elements = JSON.parse(data.result.value)
117      self.p.done("els", self.stats.unused.elements)
118    })
119  })
120}
121
122Run.prototype._onElsDone = function() {
123  this.stats.unused.bytes = { total: 0, list: [] }
124  var bytes = this.stats.unused.bytes
125  var unusedEls = this.stats.unused.elements
126  for (var i = 0; i < unusedEls.length; i++) {
127    obj = find(unusedEls[i].images, this.stats.requests, "url")
128
129    if ( obj ) {
130       bytes.list.push(obj)
131       bytes.total += parseInt(obj.contentLength)
132       obj.humanWeight = prettyBytes(parseInt(obj.contentLength))
133    }
134  }
135  bytes.humanWeight = prettyBytes(bytes.total)
136  this.p.done()
137}
138
139Run.prototype._onRequestsDone = function(requests) {
140  // aggregate network stats!
141  for (var i = 0; i < requests.length; i++) {
142    if ( requests[i].contentLength ) {
143      this.stats.network.total += parseInt(requests[i].contentLength)
144      this.stats.network.typesUsage[requests[i].type].weight += parseInt(requests[i].contentLength)
145    }
146    this.stats.network.typesUsage[requests[i].type].count++
147  }
148  this.stats.network.humanTotal = prettyBytes(this.stats.network.total)
149  
150  for (var k in this.stats.network.typesUsage) {
151    var type = this.stats.network.typesUsage[k]
152    type.humanWeight = prettyBytes(type.weight)
153  }
154  
155  this.p.done()
156}
157
158Run.prototype._onDone = function() {
159  this.chrome.close()
160  this.opts.cb(false, this.stats)
161}
162
163module.exports = Run
164
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)