UNPKG

2.11 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 {!EmulationManager.Viewport} viewport
29 * @return {Promise<boolean>}
30 */
31 async emulateViewport(viewport) {
32 const mobile = viewport.isMobile || false;
33 const width = viewport.width;
34 const height = viewport.height;
35 const deviceScaleFactor = viewport.deviceScaleFactor || 1;
36 /** @type {Protocol.Emulation.ScreenOrientation} */
37 const screenOrientation = viewport.isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };
38 const hasTouch = viewport.hasTouch || false;
39
40 await Promise.all([
41 this._client.send('Emulation.setDeviceMetricsOverride', { mobile, width, height, deviceScaleFactor, screenOrientation }),
42 this._client.send('Emulation.setTouchEmulationEnabled', {
43 enabled: hasTouch
44 })
45 ]);
46
47 const reloadNeeded = this._emulatingMobile !== mobile || this._hasTouch !== hasTouch;
48 this._emulatingMobile = mobile;
49 this._hasTouch = hasTouch;
50 return reloadNeeded;
51 }
52}
53
54/**
55 * @typedef {Object} EmulationManager.Viewport
56 * @property {number} width
57 * @property {number} height
58 * @property {number=} deviceScaleFactor
59 * @property {boolean=} isMobile
60 * @property {boolean=} isLandscape
61 * @property {boolean=} hasTouch
62 */
63
64module.exports = EmulationManager;