How to use browserContexts method in Puppeteer

Best JavaScript code snippet using puppeteer

browsercontext.js

Source:browsercontext.js Github

copy

Full Screen

...19 await helper.end()20})21test.serial('BrowserContext should have default context', async t => {22 const { browser, server } = t.context23 t.is(browser.browserContexts().length, 1)24 const defaultContext = browser.browserContexts()[0]25 t.false(defaultContext.isIncognito())26 let error = null27 await defaultContext.close().catch(e => (error = e))28 t.is(browser.defaultBrowserContext(), defaultContext)29 t.true(error.message.includes('cannot be closed'))30})31test.serial('BrowserContext should create new incognito context', async t => {32 const { browser, server } = t.context33 t.is(browser.browserContexts().length, 1)34 const context = await browser.createIncognitoBrowserContext()35 t.true(context.isIncognito())36 t.is(browser.browserContexts().length, 2)37 t.true(browser.browserContexts().indexOf(context) !== -1)38 await context.close()39 t.is(browser.browserContexts().length, 1)40})41test.serial(42 'BrowserContext should close all belonging targets once closing context',43 async t => {44 const { browser, server } = t.context45 const testResult = (await browser.pages()).length46 t.is(testResult, 1)47 const context = await browser.createIncognitoBrowserContext()48 await context.newPage()49 const testResult1 = (await browser.pages()).length50 t.is(testResult1, 2)51 const testResult2 = (await context.pages()).length52 t.is(testResult2, 1)53 await context.close()54 const testResult3 = (await browser.pages()).length55 t.is(testResult3, 1)56 }57)58test.serial(59 'BrowserContext window.open should use parent tab context',60 async t => {61 const { browser, server } = t.context62 const context = await browser.createIncognitoBrowserContext()63 const page = await context.newPage()64 await page.goto(server.EMPTY_PAGE)65 const [popupTarget] = await Promise.all([66 utils.waitEvent(browser, 'targetcreated'),67 page.evaluate(url => window.open(url), server.EMPTY_PAGE)68 ])69 t.is(popupTarget.browserContext(), context)70 await context.close()71 }72)73test.serial('BrowserContext should fire target events', async t => {74 const { browser, server } = t.context75 const context = await browser.createIncognitoBrowserContext()76 const events = []77 context.on('targetcreated', target => events.push('CREATED: ' + target.url()))78 context.on('targetchanged', target => events.push('CHANGED: ' + target.url()))79 context.on('targetdestroyed', target =>80 events.push('DESTROYED: ' + target.url())81 )82 const page = await context.newPage()83 await page.goto(server.EMPTY_PAGE)84 await page.close()85 t.deepEqual(events, [86 'CREATED: about:blank',87 `CHANGED: ${server.EMPTY_PAGE}`,88 `DESTROYED: ${server.EMPTY_PAGE}`89 ])90 await context.close()91})92test.serial('BrowserContext should wait for a target', async t => {93 const { browser, server } = t.context94 const context = await browser.createIncognitoBrowserContext()95 let resolved = false96 const targetPromise = context.waitForTarget(97 target => target.url() === server.EMPTY_PAGE98 )99 targetPromise.then(() => (resolved = true))100 const page = await context.newPage()101 t.false(resolved)102 await page.goto(server.EMPTY_PAGE)103 const target = await targetPromise104 const testResult = await target.page()105 t.is(testResult, page)106 await context.close()107})108test.serial(109 'BrowserContext should timeout waiting for a non-existent target',110 async t => {111 const { browser, server } = t.context112 const context = await browser.createIncognitoBrowserContext()113 const error = await context114 .waitForTarget(target => target.url() === server.EMPTY_PAGE, {115 timeout: 1116 })117 .catch(e => e)118 t.true(error instanceof TimeoutError)119 await context.close()120 }121)122test.serial(123 'BrowserContext should isolate localStorage and cookies',124 async t => {125 const { browser, server } = t.context126 // Create two incognito contexts.127 const context1 = await browser.createIncognitoBrowserContext()128 const context2 = await browser.createIncognitoBrowserContext()129 t.is(context1.targets().length, 0)130 t.is(context2.targets().length, 0)131 // Create a page in first incognito context.132 const page1 = await context1.newPage()133 await page1.goto(server.EMPTY_PAGE)134 await page1.evaluate(() => {135 localStorage.setItem('name', 'page1')136 document.cookie = 'name=page1'137 })138 t.is(context1.targets().length, 1)139 t.is(context2.targets().length, 0)140 // Create a page in second incognito context.141 const page2 = await context2.newPage()142 await page2.goto(server.EMPTY_PAGE)143 await page2.evaluate(() => {144 localStorage.setItem('name', 'page2')145 document.cookie = 'name=page2'146 })147 t.is(context1.targets().length, 1)148 t.is(context1.targets()[0], page1.target())149 t.is(context2.targets().length, 1)150 t.is(context2.targets()[0], page2.target())151 // Make sure pages don't share localstorage or cookies.152 const testResult = await page1.evaluate(() => localStorage.getItem('name'))153 t.is(testResult, 'page1')154 const testResult1 = await page1.evaluate(() => document.cookie)155 t.is(testResult1, 'name=page1')156 const testResult2 = await page2.evaluate(() => localStorage.getItem('name'))157 t.is(testResult2, 'page2')158 const testResult3 = await page2.evaluate(() => document.cookie)159 t.is(testResult3, 'name=page2')160 // Cleanup contexts.161 await Promise.all([context1.close(), context2.close()])162 t.is(browser.browserContexts().length, 1)163 }164)165test.serial('BrowserContext should work across sessions', async t => {166 const { browser, server } = t.context167 t.is(browser.browserContexts().length, 1)168 const context = await browser.createIncognitoBrowserContext()169 t.is(browser.browserContexts().length, 2)170 const remoteBrowser = await helper.newBrowser(browser.wsEndpoint())171 const contexts = remoteBrowser.browserContexts()172 t.is(contexts.length, 2)173 await remoteBrowser.disconnect()174 await context.close()...

Full Screen

Full Screen

PuppeteerEnvironment.js

Source:PuppeteerEnvironment.js Github

copy

Full Screen

...105 config.browserContext === 'default' ||106 !config.browserContext107 ) {108 /**109 * Since this is a new browser, browserContexts() will return only one instance110 * https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#browserbrowsercontexts111 */112 this.global.context = await this.global.browser.browserContexts()[0];113 } else {114 throw new Error(115 `browserContext should be either 'incognito' or 'default'. Received '${config.browserContext}'`,116 )117 }118 if (config.keepTabOpen != 'true') {119 await this.global.jestPuppeteer.resetPage()120 }121 },122 keepTabOpened: async () => {123 if (config.browserContext === 'incognito') {124 this.global.context = await this.global.browser.createIncognitoBrowserContext();125 } else126 if (config.browserContext === 'default' || !config.browserContext) {127 this.global.context = await this.global.browser.browserContexts()[0];128 if (config.keepTabOpen === 'true') {129 const list = await this.global.browser.pages();130 if (list.length < 2) {131 this.global.page = await this.global.context.newPage();132 }133 else {134 this.global.page = list[1];135 }136 }137 }138 else {139 throw new Error(`browserContext should be either 'incognito' or 'default'. Received '${config.browserContext}'`);140 }141 },...

Full Screen

Full Screen

browsercontext.spec.js

Source:browsercontext.spec.js Github

copy

Full Screen

...20 const {it, fit, xit} = testRunner;21 const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;22 describe('BrowserContext', function() {23 it('should have default context', async function({browser, server}) {24 expect(browser.browserContexts().length).toBe(1);25 const defaultContext = browser.browserContexts()[0];26 expect(defaultContext.isIncognito()).toBe(false);27 let error = null;28 await defaultContext.close().catch(e => error = e);29 expect(error.message).toContain('cannot be closed');30 });31 it('should create new incognito context', async function({browser, server}) {32 expect(browser.browserContexts().length).toBe(1);33 const context = await browser.createIncognitoBrowserContext();34 expect(context.isIncognito()).toBe(true);35 expect(browser.browserContexts().length).toBe(2);36 expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);37 await context.close();38 expect(browser.browserContexts().length).toBe(1);39 });40 it('should close all belonging targets once closing context', async function({browser, server}) {41 expect((await browser.pages()).length).toBe(1);42 const context = await browser.createIncognitoBrowserContext();43 await context.newPage();44 expect((await browser.pages()).length).toBe(2);45 expect((await context.pages()).length).toBe(1);46 await context.close();47 expect((await browser.pages()).length).toBe(1);48 });49 it('window.open should use parent tab context', async function({browser, server}) {50 const context = await browser.createIncognitoBrowserContext();51 const page = await context.newPage();52 await page.goto(server.EMPTY_PAGE);53 const [popupTarget] = await Promise.all([54 utils.waitEvent(browser, 'targetcreated'),55 page.evaluate(url => window.open(url), server.EMPTY_PAGE)56 ]);57 expect(popupTarget.browserContext()).toBe(context);58 await context.close();59 });60 it('should fire target events', async function({browser, server}) {61 const context = await browser.createIncognitoBrowserContext();62 const events = [];63 context.on('targetcreated', target => events.push('CREATED: ' + target.url()));64 context.on('targetchanged', target => events.push('CHANGED: ' + target.url()));65 context.on('targetdestroyed', target => events.push('DESTROYED: ' + target.url()));66 const page = await context.newPage();67 await page.goto(server.EMPTY_PAGE);68 await page.close();69 expect(events).toEqual([70 'CREATED: about:blank',71 `CHANGED: ${server.EMPTY_PAGE}`,72 `DESTROYED: ${server.EMPTY_PAGE}`73 ]);74 await context.close();75 });76 it('should isolate localStorage and cookies', async function({browser, server}) {77 // Create two incognito contexts.78 const context1 = await browser.createIncognitoBrowserContext();79 const context2 = await browser.createIncognitoBrowserContext();80 expect(context1.targets().length).toBe(0);81 expect(context2.targets().length).toBe(0);82 // Create a page in first incognito context.83 const page1 = await context1.newPage();84 await page1.goto(server.EMPTY_PAGE);85 await page1.evaluate(() => {86 localStorage.setItem('name', 'page1');87 document.cookie = 'name=page1';88 });89 expect(context1.targets().length).toBe(1);90 expect(context2.targets().length).toBe(0);91 // Create a page in second incognito context.92 const page2 = await context2.newPage();93 await page2.goto(server.EMPTY_PAGE);94 await page2.evaluate(() => {95 localStorage.setItem('name', 'page2');96 document.cookie = 'name=page2';97 });98 expect(context1.targets().length).toBe(1);99 expect(context1.targets()[0]).toBe(page1.target());100 expect(context2.targets().length).toBe(1);101 expect(context2.targets()[0]).toBe(page2.target());102 // Make sure pages don't share localstorage or cookies.103 expect(await page1.evaluate(() => localStorage.getItem('name'))).toBe('page1');104 expect(await page1.evaluate(() => document.cookie)).toBe('name=page1');105 expect(await page2.evaluate(() => localStorage.getItem('name'))).toBe('page2');106 expect(await page2.evaluate(() => document.cookie)).toBe('name=page2');107 // Cleanup contexts.108 await Promise.all([109 context1.close(),110 context2.close()111 ]);112 expect(browser.browserContexts().length).toBe(1);113 });114 it('should work across sessions', async function({browser, server}) {115 expect(browser.browserContexts().length).toBe(1);116 const context = await browser.createIncognitoBrowserContext();117 expect(browser.browserContexts().length).toBe(2);118 const remoteBrowser = await puppeteer.connect({119 browserWSEndpoint: browser.wsEndpoint()120 });121 const contexts = remoteBrowser.browserContexts();122 expect(contexts.length).toBe(2);123 await remoteBrowser.disconnect();124 await context.close();125 });126 });...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import { reactive, watchEffect } from '@nuxtjs/composition-api'2// Expose the Web Worker using Comlink (via webpack-loader)3// https://github.com/GoogleChromeLabs/comlink-loader#singleton-mode4import { CrossBrowserScreenshot } from '@/workers/playwright.worker'5// import { remote } from 'electron'6// Keep track of all the open browser contexts7// This data can be accessed reactively8export const browserContexts = reactive({9 active: [],10})11// Log changes to the browser contextss12watchEffect(() => console.log('browser contexts', browserContexts.active))13export async function takeScreenshots(14 { url = '', browsers = [], height = 0, width = 0, x = 0, y = 0 },15 callback = () => {}16) {17 const screenshotPromiseGenerator = async (browserName) => {18 // NOTE: The following NEEDS to have the await beforehand19 // It is communicating with a Web Worker via Comlink20 const instance = await new CrossBrowserScreenshot({21 url,22 browser: browserName,23 height,24 width,25 x,26 y,27 // isPackaged: remote.app.isPackaged,28 }).catch((err) => {29 console.error(err)30 })31 const { contextId } = instance32 try {33 // Track the context34 browserContexts.active.push({ id: contextId, type: browserName })35 // Take the screenshot36 const screenshots = await instance.takeScreenshot()37 // Stop tracking this context38 removeBrowserContext(contextId)39 return { type: browserName, img: screenshots }40 } catch (err) {41 removeBrowserContext(contextId)42 console.error(err)43 }44 // Remove this ID from the list of active45 function removeBrowserContext(id) {46 browserContexts.active = browserContexts.active.filter(47 (i) => !i.id === id48 )49 }50 }51 // Loop through each browser52 // Store a promise for each browser53 const promises = browsers.map(screenshotPromiseGenerator)54 // Trigger callback (optional) every time one finishes55 promises.forEach((promise) => {56 promise.then((d) => {57 if (!d) return false58 console.log('browser finished', d)59 callback(d)60 })61 })62 // Wait until they all complete63 const data = await Promise.all(promises)64 console.log(data)65 return data66}67// Convert an image buffer into base6468export function toBase64Image(image) {69 const output = image.toString('base64')70 return `data:image/png;base64, ${output}`71}72// A single browser's screenshot73// class CrossBrowserScreenshot {74// constructor(options) {75// this.url = options.url || 'https://google.com'76// this.browser = ['chromium', 'webkit', 'firefox'].includes(options.browser)77// ? options.browser78// : 'chromium' // Default to Chromium79// this.height = options.height || 10080// this.width = options.width || 10081// this.x = options.x || 082// this.y = options.y || 083// this.isLoading = true // Initial state84// }85// async takeScreenshot() {86// const id = uuid()87// console.log(`Preparing to launch ${this.browser}, ${id}`)88// this.isLoading = true // Update loading state89// const browser = await playwright[this.browser].launch({90// /* headless: false */91// })92// const context = await browser.newContext({93// viewport: {94// height: this.height,95// width: this.width,96// },97// })98// // Track the context99// browserContexts.active.push({ id, context, type: this.browser })100// // Remove this ID from the list of active101// function removeBrowserContext(id) {102// browserContexts.active = browserContexts.active.filter(103// (i) => !i.id === id104// )105// }106// try {107// console.log(`Loading ${this.browser}, ${id}`)108// const page = await context.newPage()109// await page.goto(this.url, {110// // waitUntil: 'networkidle',111// })112// console.log('x,y', [this.x, this.y])113// // Scroll up/down as needed114// await page.evaluate(`window.scrollTo(${this.x}, ${this.y})`)115// // Wait...116// await page.waitForTimeout(1000)117// const screenshotBuffer = await page.screenshot({118// // clip: {119// // x: 0,120// // y: 0,121// // height: this.height,122// // width: this.width,123// // },124// })125// removeBrowserContext(id) // Remove from the array of active browsers126// await browser.close()127// return screenshotBuffer128// } catch (err) {129// this.isLoading = false130// removeBrowserContext(id)131// await browser.close()132// console.log(err)133// return false134// }135// }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const browserContext = await browser.createIncognitoBrowserContext();5 const page = await browserContext.newPage();6 await page.screenshot({path: 'example.png'});7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch();12 const browserContext = await browser.createIncognitoBrowserContext();13 const page = await browserContext.newPage();14 await page.screenshot({path: 'example.png'});15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch();20 const browserContext = await browser.createIncognitoBrowserContext();21 const page = await browserContext.newPage();22 await page.screenshot({path: 'example.png'});23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch();28 const browserContext = await browser.createIncognitoBrowserContext();29 const page = await browserContext.newPage();30 await page.screenshot({path: 'example.png'});31 await browser.close();32})();33const puppeteer = require('puppeteer');34(async () => {35 const browser = await puppeteer.launch();36 const browserContext = await browser.createIncognitoBrowserContext();37 const page = await browserContext.newPage();38 await page.screenshot({path: 'example.png'});39 await browser.close();40})();41const puppeteer = require('puppeteer');42(async () => {43 const browser = await puppeteer.launch();44 const browserContext = await browser.createIncognitoBrowserContext();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const browserContexts = await browser.browserContexts();5 console.log(browserContexts);6 await browser.close();7})();8[ Browser {9 _targets: Map {},10 _connection: Connection {

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer')2const devices = require('puppeteer/DeviceDescriptors')3async function run() {4 const browser = await puppeteer.launch()5 const context = await browser.createIncognitoBrowserContext()6 const page = await context.newPage()7 await page.emulate(devices['iPhone 6'])8 await page.screenshot({path: 'google.png'})9 await browser.close()10}11run()12const puppeteer = require('puppeteer')13const devices = require('puppeteer/DeviceDescriptors')14async function run() {15 const browser = await puppeteer.launch()16 const context = await browser.createIncognitoBrowserContext()17 const page = await context.newPage()18 await page.emulate(devices['iPhone 6'])19 await page.screenshot({path: 'google.png'})20 await page.screenshot({path: 'facebook.png'})21 await browser.close()22}23run()

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3const browser = await puppeteer.launch();4const browserContexts = await browser.browserContexts();5console.log(browserContexts);6await browser.close();7})();8 BrowserContext {9 _events: [Object: null prototype] {},10 _connection: Connection {

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const context = await browser.createIncognitoBrowserContext();6 const page = await context.newPage();7 await page.screenshot({ path: 'google.png' });8 await browser.close();9})();10const puppeteer = require('puppeteer');11(async () => {12 const browser = await puppeteer.launch({13 });14 const context = await browser.createIncognitoBrowserContext();15 const page = await context.newPage();16 await page.screenshot({ path: 'google.png' });17 await browser.close();18})();19const puppeteer = require('puppeteer');20(async () => {21 const browser = await puppeteer.launch({22 });23 const context = await browser.createIncognitoBrowserContext();24 const page = await context.newPage();25 await page.screenshot({ path: 'google.png' });26 await browser.close();27})();28const puppeteer = require('puppeteer');29(async () => {30 const browser = await puppeteer.launch({31 });32 const context = await browser.createIncognitoBrowserContext();33 const page = await context.newPage();34 await page.screenshot({ path:

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const context = await browser.createIncognitoBrowserContext();5 const page = await context.newPage();6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch();11 const context = await browser.createIncognitoBrowserContext();12 const page = await context.newPage();13 await browser.close();14})();15const puppeteer = require('puppeteer');16(async () => {17 const browser = await puppeteer.launch();18 const context = await browser.createIncognitoBrowserContext();19 const page = await context.newPage();20 await browser.close();21})();22const puppeteer = require('puppeteer');23(async () => {24 const browser = await puppeteer.launch();25 const context = await browser.createIncognitoBrowserContext();26 const page = await context.newPage();27 await browser.close();28})();29const puppeteer = require('puppeteer');30(async () => {31 const browser = await puppeteer.launch();32 const context = await browser.createIncognitoBrowserContext();33 const page = await context.newPage();34 await browser.close();35})();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful