EmulationManager.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. class EmulationManager {
  17. /**
  18. * @param {!Puppeteer.CDPSession} client
  19. */
  20. constructor(client) {
  21. this._client = client;
  22. this._emulatingMobile = false;
  23. this._hasTouch = false;
  24. }
  25. /**
  26. * @param {!Puppeteer.Viewport} viewport
  27. * @return {Promise<boolean>}
  28. */
  29. async emulateViewport(viewport) {
  30. const mobile = viewport.isMobile || false;
  31. const width = viewport.width;
  32. const height = viewport.height;
  33. const deviceScaleFactor = viewport.deviceScaleFactor || 1;
  34. /** @type {Protocol.Emulation.ScreenOrientation} */
  35. const screenOrientation = viewport.isLandscape ? { angle: 90, type: 'landscapePrimary' } : { angle: 0, type: 'portraitPrimary' };
  36. const hasTouch = viewport.hasTouch || false;
  37. await Promise.all([
  38. this._client.send('Emulation.setDeviceMetricsOverride', { mobile, width, height, deviceScaleFactor, screenOrientation }),
  39. this._client.send('Emulation.setTouchEmulationEnabled', {
  40. enabled: hasTouch
  41. })
  42. ]);
  43. const reloadNeeded = this._emulatingMobile !== mobile || this._hasTouch !== hasTouch;
  44. this._emulatingMobile = mobile;
  45. this._hasTouch = hasTouch;
  46. return reloadNeeded;
  47. }
  48. }
  49. module.exports = {EmulationManager};