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

我想用Node.js来模拟一个移动浏览器,这意味着所有的移动浏览器function应该可以在JavaScript端(在客户端)使用,即使它们被嘲弄。

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

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

…然后当页面在模拟中加载时,主体内容应该是Mobile

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

 window.ontouchstart = function () {}; 

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

什么是创build一个浏览器的最好方法,这些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> 

使用node-horseman 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(); 

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

它只是显示window.orientation不可用,因为它不是一个手机浏览器。

正如你所提到的Phantom和Horseman,我相信你需要一个带有移动支持的浏览器自动化框架。 您可以使用铬(ChromeDriver)而不是Phantom使用selenium,并且chrome支持移动模拟。

在这里,您可以findNodeJS的selenium客户端: https ://www.npmjs.com/package/selenium-webdriverselenium驱动程序chrome驱动程序: 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(); 

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

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

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

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