【发布时间】:2020-01-01 02:42:34
【问题描述】:
每当用户单击扩展程序图标时,我都会编写一个扩展程序来模拟移动设备。这只是扩展的第一个版本,因此所有内容都是硬编码的。
我基本上成功地附加到 Chrome 当前选项卡,但我不知道为什么我的命令不能按预期工作。我使用 Chrome version 79 和 protocolversion 命令是 1.3。我目前实施的步骤是:
- 附加到当前的 chrome 标签。
- 使用 Browser.getVersion 检查我是否使用了正确的协议版本
- 使用 Emulation.canEmulate 确保 chrome 可以模拟移动设备。
- 使用 Emulation.clearDeviceMetricsOverride 清除所有指标(如果有)。
- 使用 Emulation.setUserAgentOverride 覆盖当前用户代理。
- 使用 Emulation.setDeviceMetricsOverride 模拟移动设备。
- 使用 Emulation.setTouchEmulationEnabled 启用触摸事件以模拟移动事件。
这是上述步骤的代码:
function EmulateMobileDevice(tabId) {
var protocolVersion = '1.3';
chrome.debugger.attach({
tabId: tabId
}, protocolVersion, function() {
if (chrome.runtime.lastError) {
alert(chrome.runtime.lastError.message);
return;
}
// Browser.getVersion
chrome.debugger.sendCommand({
tabId: tabId
}, "Browser.getVersion", {}, function(response) {
console.log(response);
});
// Emulation.canEmulate
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.canEmulate", {}, function(response) {
console.log(response);
});
// Emulation.clearDeviceMetricsOverride
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.clearDeviceMetricsOverride", {}, function(response) {
console.log(response);
// Emulation.setUserAgentOverride
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.setUserAgentOverride", {
userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
acceptLanguage: 'en',
platform: 'mobile'
}, function(response) {
console.log(response);
//Emulation.setDeviceMetricsOverride
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.setDeviceMetricsOverride", {
width: 0,
height: 0,
deviceScaleFactor: 0,
mobile: true,
screenOrientation: { type: 'portraitPrimary', angle: 1}
}, function(response) {
console.log(response);
// Emulation.setTouchEmulationEnabled
chrome.debugger.sendCommand({
tabId: tabId
}, "Emulation.setTouchEmulationEnabled", {
enabled: true
}, function(response) {
console.log(response);
});
});
});
}); });}
我参考了 @paulirish 实现的相同想法 here,但他在协议版本 1.1 中进行了演示,该版本目前已被弃用。我还阅读了来自here 的协议版本 1.3 的文档。 不幸的是,我无法让它工作。
这是我登录上述方法的后台脚本的屏幕截图。
非常感谢。
【问题讨论】:
-
您可以 listen to protocol 在 devtools 中手动执行设备仿真并检查命令及其参数。我想你应该指定实际的宽度/高度,而不是 0。
-
谢谢@wOxxOm,我试过了还是不行。有人知道吗?
标签: google-chrome-extension google-chrome-devtools