首页 > 解决方案 > 发送命令“Emulation.setDeviceMetricsOverride”在 chrome.debugger 中不起作用

问题描述

每当用户单击扩展程序图标时,我都会编写一个扩展程序来模拟移动设备。这只是扩展的第一个版本,因此所有内容都是硬编码的。

我基本上成功地附加到 Chrome 当前选项卡,但我不知道为什么我的命令不能按预期工作。我使用 Chrome版本 79protocolversion 命令是 1.3。我目前实施的步骤是:

  1. 附加到当前的 chrome 选项卡。
  2. 使用Browser.getVersion检查我是否使用了正确的协议版本
  3. 使用Emulation.canEmulate确保 chrome 可以模拟移动设备。
  4. 使用Emulation.clearDeviceMetricsOverride清除所有指标(如果有)。
  5. 使用Emulation.setUserAgentOverride覆盖当前用户代理。
  6. 使用Emulation.setDeviceMetricsOverride模拟移动设备。
  7. 使用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 实现的相同想法,但他在协议版本 1.1 中进行了演示,该版本目前已被弃用。我还从这里阅读了协议版本 1.3 的文档。不幸的是,我无法让它工作。

这是我登录上述方法的后台脚本的屏幕截图。

在此处输入图像描述

非常感谢。

标签: google-chrome-extensiongoogle-chrome-devtools

解决方案


如果您可以简要介绍一下您想对您的代码做些什么,这会有所帮助,

到目前为止,代码只会按原样显示选项卡,因为当宽度、高度和 deviceScaleFactor 设置为“0”(零)时,它会将网站设置为默认大小,但由于您指定了移动设备,因此默认滚动条会更改(它可能会根据您的 css 隐藏)。


推荐阅读