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



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

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

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

那么在模拟中加载页面时,正文内容应该是Mobile

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

window.ontouchstart = function () {};

我本来想使用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>

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

这会输出Not mobile,而用户代理是我提供的(iPhone 6)。应为Mobile

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

正如您提到的Phantom和Horseman,我相信您想要一个支持移动的浏览器自动化框架。您可以将硒与chrome(ChromeDriver)一起使用,而不是使用Phantom,并且chrome支持移动模拟。

在这里,您可以找到NodeJS的selenium客户端:https://www.npmjs.com/package/selenium-webdriver硒铬驱动程序: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();

在这里,您可以找到可用设备的列表: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

2021年的更新:

要使用硒网络驱动程序的模拟模式,现在正确的方法是:

var webdriver = require('selenium-webdriver'),
var driver = new webdriver.Builder()
.forBrowser('chrome')
.setChromeOptions(new chrome.Options()
.setMobileEmulation({deviceName: 'Apple iPhone 5'})
//.setMobileEmulation({deviceName: ‘Pixel 2 XL’})         //<--- tested
//.setMobileEmulation({deviceName: ‘Google Nexus 7’})
//.addArguments('start-maximized')
)
.build();
//Rest of the operations will be done in emulation mode
// this links shows what user agent you are currently using
driver.get('https://www.whatismybrowser.com/detect/what-is-my-user-agent');
driver.quit();

最新更新