首页 > 解决方案 > 如何将 Firefox 的视口设置为小于 450 像素的宽度?

问题描述

我正在尝试在 Firefox 中使用 Selenium 以正常视图(不是无头)运行一些自动化测试。我想将视口设置为width=375, height=812(iPhone X),但从 Firefox 75 开始,他们将最小宽度设置为 450 像素(Firefox 错误跟踪器)。

我读过一些帖子说您可以使用该userChrome.css文件来修改此设置,但它们似乎只适用于 Linux,而不适用于 macOS 或 Windows 10。

如何强制 Firefox 允许我设置小于 450 像素的视口?

标签: seleniumselenium-webdriverfirefoxselenium-firefoxdriver

解决方案


profile.zip解决方案是使用chrome/userChrome.css以下内容创建一个:

#main-window:not([chromehidden~="toolbar"]) {
    min-width: 50px !important;
}

和一个user.js具有以下内容:

user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", true);

profile.zip 需要作为 base64 编码字符串提供给远程 Web 驱动程序。不确定这是如何在硒中完成的。

PHP Web 驱动解决方案

很多意大利面条代码,但这对我来说是使用 php web-driver 库的。创建配置文件并再次解压缩配置文件,然后添加userChrome.css. 在 macOS 上测试:

// create firefox profile zip
$profileZipPath = __DIR__ . '/profile.zip';
$firefoxProfile = new FirefoxProfile();
$firefoxProfile->setPreference('toolkit.legacyUserProfileCustomizations.stylesheets', true);
$firefoxProfile = $firefoxProfile->encode();
file_put_contents($profileZipPath, base64_decode($firefoxProfile));
 
// unpack profile zp
$zip = new \ZipArchive();
$zip->open($profileZipPath);
$profilePath = __DIR__ . '/profile';
$zip->extractTo($profilePath);

// add chrome/userChrome.css
$cssDirectory = $profilePath . '/chrome';
mkdir($cssDirectory);
file_put_contents($cssDirectory . '/userChrome.css', <<<EOT
#main-window:not([chromehidden~="toolbar"]) {
    min-width: 50px !important;
}
EOT
);

// create profile zip
$zip = new \ZipArchive();
$zip->open($profileZipPath, \ZipArchive::CREATE);

$dir = new \RecursiveDirectoryIterator($profilePath);
$files = new \RecursiveIteratorIterator($dir);

$dir_prefix = preg_replace(
    '#\\\\#',
    '\\\\\\\\',
    $profilePath . DIRECTORY_SEPARATOR
);

foreach ($files as $name => $object) {
    if (is_dir($name)) {
         continue;
    }

    $path = preg_replace("#^{$dir_prefix}#", '', $name);
    $zip->addFile($name, $path);
}
$zip->close();

// use the new profile
$firefoxProfile = base64_encode(file_get_contents($profileZipPath));
$capabilities = DesiredCapabilities::firefox();
$capabilities->setCapability(FirefoxDriver::PROFILE => $firefoxProfile);

// ...

推荐阅读