如何使用Node.js模拟移动环境?

Ion*_*zău 10 javascript mobile node.js

我想模拟使用的移动浏览器Node.js,这意味着所有移动浏览器功能都应该在JavaScript侧面(在客户端上)可用,即使它们被模拟.

网页应该认为它们是在移动环境中加载的.例如,如果我们有一个网页说:

if ('ontouchstart' in window) {
  document.body.innerHTML = "Mobile";
} else {
  document.body.innerHTML = "Not mobile";
}
Run Code Online (Sandbox Code Playgroud)

...然后当在模拟中加载页面时,正文内容应该是Mobile.

这样做的正确方法是什么?我会避免简单地使用PhantomJS(或任何类似的东西)执行一个脚本来执行:

window.ontouchstart = function () {};
Run Code Online (Sandbox Code Playgroud)

我正在考虑使用JSDom,但它看起来没有简单的方法来说明mobile:true哪些会添加所有这些属性.

什么是创建浏览器的最佳方式,这些浏览器会API暴露这些,模拟移动浏览器?

一个更好的例子

从Node.js方面,我想与浏览器仿真进行通信,并获得一些结果.假设我们有一个index.html这样的页面:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
    </head>
    <body>
        <script>
        if ('ontouchstart' in window && window.orientation) {
          document.body.innerHTML = "Mobile";
        } else {
          document.body.innerHTML = "Not mobile";
        }
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

使用node-horseman(使用Phantomjs),我们可以执行以下操作:

const Horseman = require('node-horseman');
const horseman = new Horseman();

const iPhone6 = "Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25";    

horseman
  .userAgent(iPhone6)
  .open('index.html')
  .evaluate(function () {
    return document.body.innerHTML;
  })
  .then(html => {
      console.log(html);
  })
  .evaluate(function () {
    return navigator.userAgent;
  })
  .then(ua => {
      console.log(ua);
  })
  .close();
Run Code Online (Sandbox Code Playgroud)

这是输出Not mobile,而用户代理是我提供的(iPhone 6).预计会是Mobile.

它只是表明它window.orientation不可用,因为它不是移动浏览器.

Ali*_*Ali 5

正如你提到的Phantom和Horseman,我相信你想要一个支持移动设备的浏览器自动化框架.您可以使用带有铬的硒(ChromeDriver)代替Phantom,而chrome则支持移动仿真.

在这里,您可以找到NodeJS的selenium客户端:https://www.npmjs.com/package/selenium-webdriver chrome driver for selenium:https://sites.google.com/a/chromium.org/chromedriver/

在移动仿真模式下启动chrome:

var webdriver = require('selenium-webdriver');
var capabilities = {
    browserName: 'chrome',
    chromeOptions: {
        mobileEmulation: {
            deviceName: 'Apple iPhone 6'
        }
    }
};

var driver = new webdriver
    .Builder()
    .withCapabilities(capabilities)
    .build();
Run Code Online (Sandbox Code Playgroud)

在这里您可以找到可用设备列表:https://stackoverflow.com/a/41104964/893432

您还可以定义自定义设备:https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation

如果你想让它无头,最新的chrome版本支持它:https: //chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md

您还可以使用selenium在真实的Android设备或模拟器上运行测试:https: //sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android