窗口管理
使用 Puppeteer 的Browser.getWindowBounds和Browser.setWindowBounds方法来管理浏览器窗口的位置和状态。
以下脚本在主800x600屏幕的默认位置打开一个窗口,然后将该窗口移动到新建的屏幕上并在此处将其最大化。之后,它会将窗口恢复到正常状态。
import puppeteer from 'puppeteer-core';
const browser = await puppeteer.launch({
args: ['--screen-info={800x600}'],
});
async function logWindowBounds() {
const bounds = await browser.getWindowBounds(windowId);
console.log(
`${bounds.left},${bounds.top}` +
` ${bounds.width}x${bounds.height}` +
` ${bounds.windowState}`,
);
}
// Create new page.
const page = await browser.newPage({type: 'window'});
const windowId = await page.windowId();
await logWindowBounds();
// Add a screen to the right of the primary screen.
const screenInfo = await browser.addScreen({
left: 800,
top: 0,
width: 1600,
height: 1200,
});
// Move the window to the newly created secondary screen.
await browser.setWindowBounds(windowId, {
left: screenInfo.left + 50,
top: screenInfo.top + 50,
width: screenInfo.width - 100,
height: screenInfo.height - 100,
});
await logWindowBounds();
// Maximize the window.
await browser.setWindowBounds(windowId, {windowState: 'maximized'});
await logWindowBounds();
// Restore the window.
await browser.setWindowBounds(windowId, {windowState: 'normal'});
await logWindowBounds();
await browser.close();
输出:
20,20 780x580 normal
850,50 1500x1100 normal
800,0 1600x1200 maximized
850,50 1500x1100 normal
调整页面内容尺寸
使用 Puppeteer 的Page.resize方法来调整浏览器窗口的大小,使内容具有指定的尺寸。
示例:
import puppeteer from 'puppeteer-core';
const browser = await puppeteer.launch({
args: ['--screen-info={800x600}'],
});
const page = (await browser.pages())[0];
// Default viewport restricts window to 800x600, so remove it.
await page.setViewport(null);
// Inner window size is updated asynchronously, so wait for
// the window size change to get reported before logging it.
const resized = page.evaluate(() => {
return new Promise(resolve => {
window.onresize = resolve;
});
});
await page.resize({contentWidth: 600, contentHeight: 400});
await resized;
const result = await page.evaluate(() => {
return (
`Inner size: ${window.innerWidth}x${window.innerHeight}\n` +
`Outer size: ${window.outerWidth}x${window.outerHeight}`
);
});
console.log(result);
await browser.close();
输出:
Inner size: 600x400
Outer size: 600x487
元素全屏
以下示例演示了如何在点击时为元素请求全屏模式。
import puppeteer from 'puppeteer-core';
const browser = await puppeteer.launch({
args: ['--screen-info={1600x1200}'],
});
const page = (await browser.pages())[0];
await page.setContent(`
<div id="click-box" style="width: 10px; height: 10px;"/>
`);
await page.evaluate(() => {
const element = document.getElementById('click-box');
element.addEventListener('click', () => {
element.requestFullscreen();
});
});
await page.click('#click-box');
const windowId = await page.windowId();
const bounds = await browser.getWindowBounds(windowId);
console.log(
`${bounds.left},${bounds.top}` +
` ${bounds.width}x${bounds.height}` +
` ${bounds.windowState}`,
);
await browser.close();
输出:
0,0 1600x1200 fullscreen