How to use createIncognitoBrowserContext method in Puppeteer

Best JavaScript code snippet using puppeteer

Run Puppeteer automation tests on LambdaTest cloud grid

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

proxy.js

Source: proxy.js Github

copy
1const puppeteer = require('puppeteer');
2
3const db = require('./models');
4
5const crawler = async () => {
6  await db.sequelize.sync();
7  try {
8    let browser = await puppeteer.launch({
9      headless: false,
10      args: ['--window-size=1920,1080', '--disable-notifications'],
11    });
12    let page = await browser.newPage();
13    await page.setViewport({
14      width: 1080,
15      height: 1080,
16    });
17    await page.goto('http://spys.one/free-proxy-list/KR/');
18    const proxies = await page.evaluate(() => {
19      const ips = Array.from(document.querySelectorAll('tr > td:first-of-type > .spy14')).map(v => v.textContent.replace(/document\.write\(.+\)/, ''));
20      const types = Array.from(document.querySelectorAll('tr > td:nth-of-type(2)'))
21        .slice(5)
22        .map(v => v.textContent);
23      const latencies = Array.from(document.querySelectorAll('tr > td:nth-of-type(6) .spy1')).map(v => v.textContent);
24      return ips.map((v, i) => {
25        return {
26          ip: v,
27          type: types[i],
28          latency: latencies[i],
29        };
30      });
31    });
32    const filtered = proxies.filter(v => v.type.startsWith('HTTP')).sort((p, c) => p.latency - c.latency);
33    await Promise.all(
34      filtered.map(async v => {
35        return db.Proxy.upsert({
36          ip: v.ip,
37          type: v.type,
38          latency: v.latency,
39        });
40      }),
41    );
42    await page.close();
43    await browser.close();
44    const fastestProxies = await db.Proxy.findAll({
45      order: [['latency', 'ASC']],
46    });
47    let browsers = [];
48    for (let i = 0; i < 10; i++) {
49      const browser = await puppeteer.launch({
50        headless: false,
51        args: ['--window-size=1920,1080', '--disable-notifications', `--proxy-server=${fastestProxies[i].ip}`],
52      });
53      const page = await browser.newPage();
54      page.goto('http://www.haiip.net/service/myip/cur_ip_chk.php');
55    }
56
57    console.log(browsers);
58    // const context = await browser.createIncognitoBrowserContext();
59    // const context2 = await browser.createIncognitoBrowserContext();
60    // const context3 = await browser.createIncognitoBrowserContext();
61    // console.log(await browser.browserContexts());
62    // page = await browser.newPage();
63    // await page.goto('https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query=%EB%82%B4+%EC%95%84%EC%9D%B4%ED%94%BC');
64    // await page.waitFor(10000);
65    // await page.close();
66    // await browser.close();
67    await db.sequelize.close();
68  } catch (e) {
69    console.error(e);
70  }
71};
72
73crawler();
74
Full Screen

index.js

Source: index.js Github

copy
1const puppeteer = require('puppeteer');
2
3const db = require('./models');
4
5const crawler = async () => {
6  await db.sequelize.sync();
7  try {
8    let browser = await puppeteer.launch({
9      headless: false,
10      args: ['--window-size=1920,1080', '--disable-notifications'],
11    });
12    let page = await browser.newPage();
13    await page.setViewport({
14      width: 1080,
15      height: 1080,
16    });
17    await page.goto('http://spys.one/free-proxy-list/KR/');
18    const proxies = await page.evaluate(() => {
19      const ips = Array.from(document.querySelectorAll('tr > td:first-of-type > .spy14')).map((v) => v.textContent.replace(/document\.write\(.+\)/, ''));
20      const types = Array.from(document.querySelectorAll('tr > td:nth-of-type(2)')).slice(5).map((v) => v.textContent);
21      const latencies = Array.from(document.querySelectorAll('tr > td:nth-of-type(6) .spy1')).map((v) => v.textContent);
22      return ips.map((v, i) => {
23        return {
24          ip: v,
25          type: types[i],
26          latency: latencies[i],
27        }
28      });
29    });
30    const filtered = proxies.filter((v) => v.type.startsWith('HTTP')).sort((p, c) => p.latency - c.latency);
31    await Promise.all(filtered.map(async (v) => {
32      return db.Proxy.upsert({
33        ip: v.ip,
34        type: v.type,
35        latency: v.latency,
36      });
37    }));
38    await page.close();
39    await browser.close();
40    const fastestProxies = await db.Proxy.findAll({
41      order: [['latency', 'ASC']],
42    });
43    browser = await puppeteer.launch({
44      headless: false,
45      args: ['--window-size=1920,1080', '--disable-notifications', `--proxy-server=${fastestProxies[0].ip}`],
46    });
47    const browser2 = await puppeteer.launch({
48      headless: false,
49      args: ['--window-size=1920,1080', '--disable-notifications', `--proxy-server=${fastestProxies[1].ip}`],
50    });
51    const browser3 = await puppeteer.launch({
52      headless: false,
53      args: ['--window-size=1920,1080', '--disable-notifications', `--proxy-server=${fastestProxies[2].ip}`],
54    });
55    // const context = await browser.createIncognitoBrowserContext();
56    // const context2 = await browser.createIncognitoBrowserContext();
57    // const context3 = await browser.createIncognitoBrowserContext();
58    // console.log(await browser.browserContexts());
59    const page1 = await browser.newPage();
60    const page2 = await browser2.newPage();
61    const page3 = await browser3.newPage();
62    await page1.goto('https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query=%EB%82%B4+%EC%95%84%EC%9D%B4%ED%94%BC');
63    await page2.goto('https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query=%EB%82%B4+%EC%95%84%EC%9D%B4%ED%94%BC');
64    await page3.goto('https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query=%EB%82%B4+%EC%95%84%EC%9D%B4%ED%94%BC');
65    // page = await browser.newPage();
66    // await page.goto('https://search.naver.com/search.naver?sm=top_hty&fbm=1&ie=utf8&query=%EB%82%B4+%EC%95%84%EC%9D%B4%ED%94%BC');
67    // await page.waitFor(10000);
68    // await page.close();
69    // await browser.close();
70    await db.sequelize.close();
71  } catch (e) {
72    console.error(e);
73  }
74};
75
76crawler();
77
Full Screen

browsercontext.spec.js

Source: browsercontext.spec.js Github

copy
1/**
2 * Copyright 2018 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17const utils = require('./utils');
18const puppeteer = utils.requireRoot('index');
19const {TimeoutError} = utils.requireRoot('Errors');
20
21module.exports.addTests = function({testRunner, expect}) {
22  const {describe, xdescribe, fdescribe} = testRunner;
23  const {it, fit, xit} = testRunner;
24  const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
25
26  describe('BrowserContext', function() {
27    it('should have default context', async function({browser, server}) {
28      expect(browser.browserContexts().length).toBe(1);
29      const defaultContext = browser.browserContexts()[0];
30      expect(defaultContext.isIncognito()).toBe(false);
31      let error = null;
32      await defaultContext.close().catch(e => error = e);
33      expect(browser.defaultBrowserContext()).toBe(defaultContext);
34      expect(error.message).toContain('cannot be closed');
35    });
36    it('should create new incognito context', async function({browser, server}) {
37      expect(browser.browserContexts().length).toBe(1);
38      const context = await browser.createIncognitoBrowserContext();
39      expect(context.isIncognito()).toBe(true);
40      expect(browser.browserContexts().length).toBe(2);
41      expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);
42      await context.close();
43      expect(browser.browserContexts().length).toBe(1);
44    });
45    it('should close all belonging targets once closing context', async function({browser, server}) {
46      expect((await browser.pages()).length).toBe(1);
47
48      const context = await browser.createIncognitoBrowserContext();
49      await context.newPage();
50      expect((await browser.pages()).length).toBe(2);
51      expect((await context.pages()).length).toBe(1);
52
53      await context.close();
54      expect((await browser.pages()).length).toBe(1);
55    });
56    it('window.open should use parent tab context', async function({browser, server}) {
57      const context = await browser.createIncognitoBrowserContext();
58      const page = await context.newPage();
59      await page.goto(server.EMPTY_PAGE);
60      const [popupTarget] = await Promise.all([
61        utils.waitEvent(browser, 'targetcreated'),
62        page.evaluate(url => window.open(url), server.EMPTY_PAGE)
63      ]);
64      expect(popupTarget.browserContext()).toBe(context);
65      await context.close();
66    });
67    it('should fire target events', async function({browser, server}) {
68      const context = await browser.createIncognitoBrowserContext();
69      const events = [];
70      context.on('targetcreated', target => events.push('CREATED: ' + target.url()));
71      context.on('targetchanged', target => events.push('CHANGED: ' + target.url()));
72      context.on('targetdestroyed', target => events.push('DESTROYED: ' + target.url()));
73      const page = await context.newPage();
74      await page.goto(server.EMPTY_PAGE);
75      await page.close();
76      expect(events).toEqual([
77        'CREATED: about:blank',
78        `CHANGED: ${server.EMPTY_PAGE}`,
79        `DESTROYED: ${server.EMPTY_PAGE}`
80      ]);
81      await context.close();
82    });
83    it('should wait for a target', async function({browser, server}) {
84      const context = await browser.createIncognitoBrowserContext();
85      let resolved = false;
86      const targetPromise = context.waitForTarget(target => target.url() === server.EMPTY_PAGE);
87      targetPromise.then(() => resolved = true);
88      const page = await context.newPage();
89      expect(resolved).toBe(false);
90      await page.goto(server.EMPTY_PAGE);
91      const target = await targetPromise;
92      expect(await target.page()).toBe(page);
93      await context.close();
94    });
95    it('should timeout waiting for a non-existent target', async function({browser, server}) {
96      const context = await browser.createIncognitoBrowserContext();
97      const error = await context.waitForTarget(target => target.url() === server.EMPTY_PAGE, {timeout: 1}).catch(e => e);
98      expect(error).toBeInstanceOf(TimeoutError);
99      await context.close();
100    });
101    it('should isolate localStorage and cookies', async function({browser, server}) {
102      // Create two incognito contexts.
103      const context1 = await browser.createIncognitoBrowserContext();
104      const context2 = await browser.createIncognitoBrowserContext();
105      expect(context1.targets().length).toBe(0);
106      expect(context2.targets().length).toBe(0);
107
108      // Create a page in first incognito context.
109      const page1 = await context1.newPage();
110      await page1.goto(server.EMPTY_PAGE);
111      await page1.evaluate(() => {
112        localStorage.setItem('name', 'page1');
113        document.cookie = 'name=page1';
114      });
115
116      expect(context1.targets().length).toBe(1);
117      expect(context2.targets().length).toBe(0);
118
119      // Create a page in second incognito context.
120      const page2 = await context2.newPage();
121      await page2.goto(server.EMPTY_PAGE);
122      await page2.evaluate(() => {
123        localStorage.setItem('name', 'page2');
124        document.cookie = 'name=page2';
125      });
126
127      expect(context1.targets().length).toBe(1);
128      expect(context1.targets()[0]).toBe(page1.target());
129      expect(context2.targets().length).toBe(1);
130      expect(context2.targets()[0]).toBe(page2.target());
131
132      // Make sure pages don't share localstorage or cookies.
133      expect(await page1.evaluate(() => localStorage.getItem('name'))).toBe('page1');
134      expect(await page1.evaluate(() => document.cookie)).toBe('name=page1');
135      expect(await page2.evaluate(() => localStorage.getItem('name'))).toBe('page2');
136      expect(await page2.evaluate(() => document.cookie)).toBe('name=page2');
137
138      // Cleanup contexts.
139      await Promise.all([
140        context1.close(),
141        context2.close()
142      ]);
143      expect(browser.browserContexts().length).toBe(1);
144    });
145    it('should work across sessions', async function({browser, server}) {
146      expect(browser.browserContexts().length).toBe(1);
147      const context = await browser.createIncognitoBrowserContext();
148      expect(browser.browserContexts().length).toBe(2);
149      const remoteBrowser = await puppeteer.connect({
150        browserWSEndpoint: browser.wsEndpoint()
151      });
152      const contexts = remoteBrowser.browserContexts();
153      expect(contexts.length).toBe(2);
154      await remoteBrowser.disconnect();
155      await context.close();
156    });
157  });
158};
159
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Puppeteer on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)