UNPKG

2.45 kBJavaScriptView Raw
1/**
2 * Copyright 2017 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17class EmulationManager {
18 /**
19 * @param {!Puppeteer.CDPSession} client
20 */
21 constructor(client) {
22 this._client = client;
23 this._emulatingMobile = false;
24 this._hasTouch = false;
25 }
26
27 /**
28 * @param {!Puppeteer.Viewport} viewport
29 * @return {Promise<boolean>}
30 */
31 /* async */ emulateViewport(viewport) {return (fn => {
32 const gen = fn.call(this);
33 return new Promise((resolve, reject) => {
34 function step(key, arg) {
35 let info, value;
36 try {
37 info = gen[key](arg);
38 value = info.value;
39 } catch (error) {
40 reject(error);
41 return;
42 }
43 if (info.done) {
44 resolve(value);
45 } else {
46 return Promise.resolve(value).then(
47 value => {
48 step('next', value);
49 },
50 err => {
51 step('throw', err);
52 });
53 }
54 }
55 return step('next');
56 });
57})(function*(){
58 const mobile = viewport.isMobile || false;
59 const width = viewport.width;
60 const height = viewport.height;
61 const deviceScaleFactor = viewport.deviceScaleFactor || 1;
62 /** @type {Protocol.Emulation.ScreenOrientation} */
63 const screenOrientation = viewport.isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };
64 const hasTouch = viewport.hasTouch || false;
65
66 (yield Promise.all([
67 this._client.send('Emulation.setDeviceMetricsOverride', { mobile, width, height, deviceScaleFactor, screenOrientation }),
68 this._client.send('Emulation.setTouchEmulationEnabled', {
69 enabled: hasTouch
70 })
71 ]));
72
73 const reloadNeeded = this._emulatingMobile !== mobile || this._hasTouch !== hasTouch;
74 this._emulatingMobile = mobile;
75 this._hasTouch = hasTouch;
76 return reloadNeeded;
77 });}
78}
79
80module.exports = {EmulationManager};