我想使用 Node.js
模拟移动浏览器,这意味着所有移动浏览器功能都应该在 JavaScript
端(在客户端)可用,即使他们被 mock 了。
网页应该认为它们是在移动环境中加载的。例如,如果我们有一个网页,上面写着:
if ('ontouchstart' in window) {
document.body.innerHTML = "Mobile";
} else {
document.body.innerHTML = "Not mobile";
}
...那么在模拟加载页面时,body内容应该是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,我相信您想要一个支持移动设备的浏览器自动化框架。您可以将 selenium 与 chrome (ChromeDriver) 一起使用而不是 Phantom,并且 chrome 支持移动仿真。
在这里你可以找到 NodeJS 的 selenium 客户端:https://www.npmjs.com/package/selenium-webdriver Selenium 的 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();
您可以在此处找到可用设备列表:https://stackoverflow.com/a/41104964/893432
您还可以定义您的自定义设备:https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation
如果您希望它 headless ,最新的 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
关于javascript - 如何使用 Node.js 模拟移动环境?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41543269/