Controlling new page puppeteer.js
In Puppeteer, you can control the behavior of a new page by using the page
object returned by the browser.newPage()
method. Here are some ways to control the behavior of a new page:
- Navigation: You can navigate to a new page by calling the
goto()
method on thepage
object. For example:const page = await browser.newPage(); await page.goto('https://example.com');
- Setting the viewport: You can set the viewport size and dimensions using the
setViewport()
method. For example:const page = await browser.newPage(); await page.setViewport({ width: 1280, height: 800 });
- Setting the user agent: You can set the user agent string using the
setUserAgent()
method. For example:const page = await browser.newPage(); await page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3');
- Disabling images: You can disable images by setting the
image
option tofalse
when creating the page. For example:const page = await browser.newPage({ image: false });
- Enabling JavaScript: You can enable JavaScript by setting the
javascriptEnabled
option totrue
when creating the page. For example:const page = await browser.newPage({ javascriptEnabled: true });
- Setting the timezone: You can set the timezone using the
setTimezone()
method. For example:const page = await browser.newPage(); await page.setTimezone('America/New_York');
- Setting the geolocation: You can set the geolocation using the
setGeolocation()
method. For example:const page = await browser.newPage(); await page.setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
- Waiting for a specific condition: You can use the
waitFor()
method to wait for a specific condition to be met. For example:const page = await browser.newPage(); await page.goto('https://example.com'); await page.waitFor('h1');
- Cancelling a navigation: You can cancel a navigation by calling the
cancel()
method on thepage
object. For example:const page = await browser.newPage(); await page.goto('https://example.com'); page.cancel();
- Closing the page: You can close the page by calling the
close()
method on thepage
object. For example:const page = await browser.newPage(); await page.goto('https://example.com'); page.close();
These are just a few examples of how you can control the behavior of a new page in Puppeteer. You can find more information in the Puppeteer documentation.