Skip to content

Instantly share code, notes, and snippets.

@regevbr
Last active February 4, 2022 21:45
Show Gist options
  • Save regevbr/d78aee687b03d6eefde8f08c3746786c to your computer and use it in GitHub Desktop.
Save regevbr/d78aee687b03d6eefde8f08c3746786c to your computer and use it in GitHub Desktop.
How to open "incognito" context in puppeteer
"use strict";
const Promise = require('bluebird');
const Page = require('puppeteer/node6/lib/Page');
function newPageWithNewContext(browser) {
let browserContextId;
let targetId;
let target;
return Promise.resolve()
.then(() => {
return browser._connection.send('Target.createBrowserContext');
})
.then(res => {
browserContextId = res.browserContextId;
return browser._connection.send('Target.createTarget', {url: 'about:blank', browserContextId});
})
.then(res => {
targetId = res.targetId;
return browser._targets.get(targetId);
})
.then(res => {
target = res;
return browser._connection.createSession(targetId);
})
.then(client => {
return Page.create(client, target, browser._ignoreHTTPSErrors, browser._appMode, browser._screenshotTaskQueue);
})
.then(page => {
page.__IncoContextData = {
browserContextId,
targetId: page._target._targetId
};
return page;
})
.catch(err => {
if (browserContextId){
browser._connection.send('Target.disposeBrowserContext', {browserContextId: browserContextId});
}
return Promise.reject(err);
});
}
function newPageWithExsitingContext(browser, IncoContextData) {
const {targetId} = IncoContextData;
let target;
return Promise.resolve()
.then(() => {
return browser._targets.get(targetId);
})
.then(res => {
target = res;
return browser._connection.createSession(targetId);
})
.then(client => {
return Page.create(client, target, browser._ignoreHTTPSErrors, browser._appMode, browser._screenshotTaskQueue);
})
.then(page => {
page.__IncoContextData = {
browserContextId: IncoContextData.browserContextId,
targetId: page._target._targetId
};
return page;
});
}
function closePage(browser, page) {
let browserContextId;
if (page.__IncoContextData && page.__IncoContextData.browserContextId) {
browserContextId = page.__IncoContextData.browserContextId;
}
return Promise.resolve()
.then(() => {
return page.close();
})
.finally(() => {
if (browserContextId) {
return browser._connection.send('Target.disposeBrowserContext', {browserContextId: page.__IncoContextData.browserContextId});
}
});
}
// browser is the instance returned form puppeteer.launch
module.exports = {
beginIncognito: browser => {
return newPageWithNewContext(browser)
.then(page => {
page.endIncognito = () => {
return closePage(browser, page);
};
return page;
});
},
addIncognitoTab: (browser, incoPage) => {
return newPageWithExsitingContext(browser, incoPage.__IncoContextData)
.then(page => {
page.endIncognito = () => {
return closePage(browser, page);
};
return page;
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment