首页 > 解决方案 > 有没有办法触发标准缩放(不是无头)

问题描述

我正在关闭无头模式运行 puppeteer,以便自动化和远程控制另一台计算机上的可见 Chromium 浏览器。

有没有办法像在 UI 菜单或ctrl +/crtl -命令中一样触发或模拟浏览器上的缩放?

注入 CSS 或使用各​​种记录在案的缩放命令并不能完全复制这一点,例如,使用vh/vw单位定义的元素不会得到调整。


我目前的解决方案

使用视口缩放在Emulation.setDeviceMetricsOverride缩小时效果很好,但它似乎是在调整页面光栅的大小而不是以目标大小呈现,导致放大时文本模糊。

调整视口大小并使用Emulation.setPageScaleFactor适用于放大,但是在我的测试中似乎忽略了小于 1 的 pageScaleFactor。

这两种解决方案的一个问题是,它需要提前知道浏览器窗口的宽度/高度,并且依赖于不改变,而不是具有流畅的视口。我也不确定我缺少标准浏览器缩放的其他哪些功能。

我的缩放代码现在是:


async applyFrameZoom(page, zoom) {
    // page is a puppeteer.Page instance
    // zoom is an integer percentage

    const session = await page.target().createCDPSession();

    let window = await session.send('Browser.getWindowForTarget', {
        targetId: page.target()._targetId
    });

    let width = window.bounds.width;
    let height = window.bounds.height;

    if (!zoom || zoom === 100) {
        // Unset any zoom
        await session.send('Emulation.clearDeviceMetricsOverride');
        await session.send('Emulation.resetPageScaleFactor');
    } else if (zoom > 100) {
        // Unset other zooming method
        await session.send('Emulation.clearDeviceMetricsOverride');

        // Zoom in by reducing size then adjusting page scale (unable to zoom out using this method)
        await page.setViewport({
            width: Math.round(width / (zoom / 100)),
            height: Math.round(height / (zoom / 100))
        });

        await session.send('Emulation.setPageScaleFactor', {
            pageScaleFactor: (zoom / 100)
        });

        await session.send('Emulation.setVisibleSize', {
            width: width,
            height: height
        });
    } else {
        // Unset other zooming method
        await session.send('Emulation.resetPageScaleFactor');

        // Zoom out by emulating a scaled device (makes text blurry when zooming in with this method)
        await session.send('Emulation.setDeviceMetricsOverride', {
            width: Math.round(width / (zoom / 100)),
            height: Math.round(height / (zoom / 100)),
            mobile: false,
            deviceScaleFactor: 1,
            dontSetVisibleSize: true,
            viewport: {
                x: 0,
                y: 0,
                width: width,
                height: height,
                scale: (zoom / 100)
            }
        });
    }

    await this.frame.waitForSelector('html');
    this.frame.evaluate(function () {
        window.dispatchEvent(new Event('resize'));
    });
}

有一个更好的方法吗?

标签: puppeteerchrome-devtools-protocol

解决方案


命令行--force-device-scale-factor选项似乎适用于缩放整个 chrome UI,无论是放大还是缩小。

使用 puppeteer 将其传递给 chrome:

puppeteer.launch({
    args: ["--force-device-scale-factor=0.5"],
    headless: false,
})

(用铬 78 / puppeteer 1.20.0 测试)


但是如果您需要在不重新启动 chrome 的情况下进行缩放或者不想缩放整个 UI,实际上有一种方法可以使用 puppeteer 触发原生 chrome 缩放。

我已经创建了一个存储库来演示这里。它的工作原理是绕过一个 chrome 扩展,它可以访问chrome.tabs.setZoom API。

chrome-extension/manifest.json

{
    "name": "my-extension-name",
    "description": "A minimal chrome extension to help puppeteer with zooming",
    "version": "1.0",
    "manifest_version": 2,
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "permissions": []
}

chrome-extension/background.js

function setZoom(tabId, zoomFactor) {
    chrome.tabs.setZoom(tabId, zoomFactor)
}

main.js

const puppeteer = require('puppeteer');

(async () => {
    const extensionPath = require('path').join(__dirname, 'chrome-extension');
    const extensionName = 'my-extension-name';

    const browser = await puppeteer.launch({
        args: [
            `--disable-extensions-except=${extensionPath}`,
            `--load-extension=${extensionPath}`
        ],
        headless: false,
    });
    const page = await browser.newPage();
    await page.goto('https://google.com');
    
    // get the background page of the extension
    const targets = await browser.targets();
    const extenstionPageTarget = targets.find(
        (target) => target._targetInfo.title === extensionName
    );
    const extensionPage = await extenstionPageTarget.page();

    // do the zooming by invoking setZoom of background.js
    const zoomFactor = 0.5
    await extensionPage.evaluate((zoomFactor) => {
        // a tabId of undefined defaults to the currently active tab
        const tabId = undefined;
        setZoom(tabId, zoomFactor);
    }, zoomFactor);
})();

我还没有找到tabId使用 puppeteer 获取页面的方法,尽管这可能再次通过扩展程序实现。但是,如果您要缩放的页面是当前活动的页面,则上述操作会起作用。

请注意,加载 chrome 扩展目前无法在 headless 模式下工作,但幸运的是,这在您的情况下不是问题。


推荐阅读