Best JavaScript code snippet using puppeteer
chrome.js
Source:chrome.js
...132 process.once('SIGHUP', killChrome)133 let criClient134 try {135 // await Promise.delay(5000)136 let listeningOn = await waitForWSEndpoint(chromeProcess, 30 * 1000)137 console.log(listeningOn)138 await delay(3000)139 criClient = await CRI(options)140 } catch (e) {141 killChrome()142 throw e143 }144 return criClient145 }146 /**147 * @desc Launch Chrome by finding an acceptable executable on the host system but do not connect to it148 * @param {?ChromeOptions} [options = {}]149 * @return {Promise<CRI>}150 */151 static async launchNoConnect (options = {}) {152 options = ensureOptions(options)153 if (options.executable == null) {154 options.executable = await ChromeFinder.findChrome()155 }156 let userDataDir = null157 if (!options.executable) {158 userDataDir = await fs.mkdtemp(CHROME_PROFILE_PATH)159 } else {160 userDataDir = options.userDataDir161 }162 const chromeArguments = chromeArgs(options, userDataDir)163 let killed = false164 const chromeProcess = cp.spawn(options.executable, chromeArguments, {165 stdio: ['ignore', 'ignore', 'pipe'],166 env: process.env,167 detached: process.platform !== 'win32'168 })169 process.on('exit', killChrome)170 chromeProcess.once('exit', maybeRemoveUDataDir)171 process.on('SIGINT', () => {172 killChrome()173 process.exit(130)174 })175 process.once('SIGTERM', killChrome)176 process.once('SIGHUP', killChrome)177 try {178 // await Promise.delay(5000)179 let listeningOn = await waitForWSEndpoint(chromeProcess, 30 * 1000)180 console.log(listeningOn)181 } catch (e) {182 killChrome()183 throw e184 }185 function maybeRemoveUDataDir () {186 if (!options.userDataDir) {187 try {188 fs.removeSync(userDataDir)189 } catch (e) {}190 }191 }192 function killChrome () {193 if (killed) {...
BrowserRunner.js
Source:BrowserRunner.js
...125 }126 async setupConnection(options) {127 const { usePipe, timeout, slowMo, preferredRevision } = options;128 if (!usePipe) {129 const browserWSEndpoint = await waitForWSEndpoint(this.proc, timeout, preferredRevision);130 const transport = await WebSocketTransport_1.WebSocketTransport.create(browserWSEndpoint);131 this.connection = new Connection_1.Connection(browserWSEndpoint, transport, slowMo);132 }133 else {134 // stdio was assigned during start(), and the 'pipe' option there adds the 4th and 5th items to stdio array135 const { 3: pipeWrite, 4: pipeRead } = this.proc.stdio;136 const transport = new PipeTransport_1.PipeTransport(pipeWrite, pipeRead);137 this.connection = new Connection_1.Connection('', transport, slowMo);138 }139 return this.connection;140 }141}142exports.BrowserRunner = BrowserRunner;143function waitForWSEndpoint(browserProcess, timeout, preferredRevision) {144 return new Promise((resolve, reject) => {145 const rl = readline.createInterface({ input: browserProcess.stderr });146 let stderr = '';147 const listeners = [148 helper_1.helper.addEventListener(rl, 'line', onLine),149 helper_1.helper.addEventListener(rl, 'close', () => onClose()),150 helper_1.helper.addEventListener(browserProcess, 'exit', () => onClose()),151 helper_1.helper.addEventListener(browserProcess, 'error', (error) => onClose(error)),152 ];153 const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;154 /**155 * @param {!Error=} error156 */157 function onClose(error) {...
initChrome.js
Source:initChrome.js
...211 process.exit(130)212 })213 process.once('SIGTERM', killChrome)214 process.once('SIGHUP', killChrome)215 await waitForWSEndpoint(chromeProcess, 15 * 1000)216 return { chromeProcess, killChrome }217}218// module.exports = initChrome219function waitForWSEndpoint (chromeProcess, timeout) {220 return new Promise((resolve, reject) => {221 const rl = readline.createInterface({ input: chromeProcess.stderr })222 let stderr = ''223 const listeners = [224 helper.addEventListener(rl, 'line', onLine),225 helper.addEventListener(rl, 'close', onClose),226 helper.addEventListener(chromeProcess, 'exit', onClose),227 helper.addEventListener(chromeProcess, 'error', onClose)228 ]229 const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0...
Runner.js
Source:Runner.js
...62 env,63 stdio: ['inherit', 'inherit', 'pipe']64 }65 );66 waitForWSEndpoint(nodeProcess, webSocket => runToolForProcess({webSocket, toolFactory, ondemand, callback}));67 await new Promise(resolve => nodeProcess.once('exit', resolve));68}69async function setupOnDemand(connection, wrapper) {70 function setupEnvironment() {71 const nativeConsoleDebug = console.debug;72 function sendCommand(command) {73 let resolveCallback;74 const promise = new Promise(resolve => resolveCallback = resolve);75 const id = setTimeout(resolve, 30000);76 function resolve() {77 resolveCallback();78 clearTimeout(id);79 }80 nativeConsoleDebug(command, resolve);81 return promise;82 }83 this.startTheTool = sendCommand.bind(null, 'thetool:start');84 this.stopTheTool = sendCommand.bind(null, 'thetool:stop');85 this.captureTheTool = sendCommand.bind(null, 'thetool:capture');86 }87 await connection.send('Runtime.evaluate', {88 expression: `(${setupEnvironment.toString()})()`89 });90 connection.on('Runtime.consoleAPICalled', async message => {91 if (message.type !== 'debug')92 return;93 if (!message.args.length)94 return;95 const arg0 = message.args[0].value;96 if (arg0 === 'thetool:start')97 await wrapper.start();98 else if (arg0 === 'thetool:stop')99 await wrapper.stop();100 else if (arg0 === 'thetool:capture')101 await wrapper.capture();102 else103 return;104 await connection.send('Runtime.callFunctionOn', {105 functionDeclaration: (function() { this(); }).toString(),106 objectId: message.args[1].objectId107 });108 });109}110async function runToolForProcess({webSocket, toolFactory, ondemand, callback}) {111 const connection = new Connection(await WebSocketTransport.create(webSocket));112 const tool = toolFactory(connection);113 const wrapper = new ToolWrapper(tool, callback);114 if (ondemand) {115 await setupOnDemand(connection, wrapper);116 await connection.send('NodeWorker.enable', {117 waitForDebuggerOnStart: true118 });119 connection.on('NodeWorker.attachedToWorker', ({sessionId}) => runToolForWorker({120 connection,121 sessionId,122 toolFactory,123 callback,124 wrapper: tool.onlyMain() ? wrapper : null125 }));126 } else {127 await wrapper.start();128 }129 await connection.send('Runtime.enable');130 let finishedCallback;131 const finishedPromise = new Promise(resolve => finishedCallback = resolve);132 connection.on('Runtime.executionContextDestroyed', message => message.executionContextId === 1 && finishedCallback());133 await connection.send('Runtime.runIfWaitingForDebugger');134 await finishedPromise;135 if (!ondemand)136 await wrapper.stop();137 await connection.close();138}139async function runToolForWorker({connection: mainConnection, sessionId, toolFactory, wrapper, callback}) {140 const connection = new Connection(new WorkerTransport(mainConnection, sessionId));141 wrapper = wrapper || new ToolWrapper(toolFactory(connection), callback);142 await setupOnDemand(connection, wrapper);143 await connection.send('Runtime.enable');144 await connection.send('Runtime.runIfWaitingForDebugger', {});145}146const blacklist = new Set([147 'Waiting for the debugger to disconnect...',148 'For help, see: https://nodejs.org/en/docs/inspector',149 'For help see: https://nodejs.org/en/docs/inspector',150 'Debugger attached.'151]);152function waitForWSEndpoint(nodeProcess, callback) {153 const rl = readline.createInterface({ input: nodeProcess.stderr });154 rl.on('line', onLine);155 rl.on('close', cleanup);156 nodeProcess.on('exit', cleanup);157 nodeProcess.on('error', cleanup);158 function cleanup() {159 rl.removeListener('line', onLine);160 rl.removeListener('close', cleanup);161 nodeProcess.removeListener('exit', cleanup);162 nodeProcess.removeListener('error', cleanup);163 }164 function onLine(line) {165 const match = line.match(/^Debugger listening on (ws:\/\/.*)$/);166 if (!match) {...
browserProcess.ts
Source:browserProcess.ts
...57 cancellationToken: CancellationToken,58) => {59 const endpoint =60 options.connection === 061 ? await waitForWSEndpoint(process, cancellationToken)62 : await retryGetBrowserEndpoint(63 `http://localhost:${options.connection}`,64 cancellationToken,65 logger,66 );67 const inspectWs = options.inspectUri68 ? constructInspectorWSUri(options.inspectUri, options.url, endpoint)69 : endpoint;70 while (true) {71 try {72 return await WebSocketTransport.create(inspectWs, cancellationToken);73 } catch (e) {74 if (cancellationToken.isCancellationRequested) {75 throw e;76 }77 await delay(200);78 }79 }80};81export class NonTrackedBrowserProcess implements IBrowserProcess {82 public readonly pid = undefined;83 public readonly onExit = new EventEmitter<number>().event;84 public readonly onError = new EventEmitter<Error>().event;85 constructor(private readonly logger: ILogger) {}86 /**87 * @inheritdoc88 */89 public async transport(90 options: ITransportOptions,91 cancellationToken: CancellationToken,92 ): Promise<ITransport> {93 return inspectWsConnection(this.logger, this, options, cancellationToken);94 }95 /**96 * @inheritdoc97 */98 public kill() {99 // noop100 }101}102/**103 * Browser process104 */105export class ChildProcessBrowserProcess implements IBrowserProcess {106 public readonly pid = undefined;107 private readonly exitEmitter = new EventEmitter<number>();108 public readonly onExit = this.exitEmitter.event;109 private readonly errorEmitter = new EventEmitter<Error>();110 public readonly onError = this.errorEmitter.event;111 constructor(112 private readonly cp: ChildProcessWithoutNullStreams,113 private readonly logger: ILogger,114 ) {115 cp.on('exit', code => this.exitEmitter.fire(code || 0));116 cp.on('error', error => this.errorEmitter.fire(error));117 }118 public get stderr() {119 return this.cp.stderr;120 }121 public get stdio() {122 return this.cp.stdio;123 }124 /**125 * @inheritdoc126 */127 public async transport(128 options: ITransportOptions,129 cancellationToken: CancellationToken,130 ): Promise<ITransport> {131 if (options.connection === 'pipe') {132 return new RawPipeTransport(133 this.logger,134 this.cp.stdio[3] as Writable,135 this.cp.stdio[4] as Readable,136 );137 }138 return inspectWsConnection(this.logger, this, options, cancellationToken);139 }140 /**141 * @inheritdoc142 */143 public kill() {144 killTree(this.cp.pid as number, this.logger);145 }146}147function waitForWSEndpoint(148 browserProcess: IBrowserProcess,149 cancellationToken: CancellationToken,150): Promise<string> {151 if (!browserProcess.stderr) {152 throw new Error('Cannot wait for a websocket for a target that lacks stderr');153 }154 return new Promise((resolve, reject) => {155 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion156 const rl = readline.createInterface({ input: browserProcess.stderr! });157 let stderr = '';158 const onClose = () => onDone();159 rl.on('line', onLine);160 rl.on('close', onClose);161 const disposable = new DisposableList([...
Launcher.js
Source:Launcher.js
...86 if (options.handleSIGINT !== false)87 process.once('SIGINT', killChrome);88 try {89 const connectionDelay = options.slowMo || 0;90 const browserWSEndpoint = await waitForWSEndpoint(chromeProcess, options.timeout || 30 * 1000);91 const connection = await Connection.create(browserWSEndpoint, connectionDelay);92 return new Browser(connection, !!options.ignoreHTTPSErrors, killChrome);93 } catch (e) {94 killChrome();95 throw e;96 }97 function killChrome() {98 if (killed)99 return;100 killed = true;101 if (process.platform === 'win32')102 childProcess.execSync(`taskkill /pid ${chromeProcess.pid} /T /F`);103 else104 chromeProcess.kill('SIGKILL');105 }106 }107 /**108 * @param {string} options109 * @return {!Promise<!Browser>}110 */111 static async connect({browserWSEndpoint, ignoreHTTPSErrors = false}) {112 const connection = await Connection.create(browserWSEndpoint);113 return new Browser(connection, !!ignoreHTTPSErrors);114 }115}116/**117 * @param {!ChildProcess} chromeProcess118 * @param {number} timeout119 * @return {!Promise<string>}120 */121function waitForWSEndpoint(chromeProcess, timeout) {122 return new Promise((resolve, reject) => {123 const rl = readline.createInterface({ input: chromeProcess.stderr });124 let stderr = '';125 const listeners = [126 helper.addEventListener(rl, 'line', onLine),127 helper.addEventListener(rl, 'close', onClose),128 helper.addEventListener(chromeProcess, 'exit', onClose)129 ];130 const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;131 function onClose() {132 cleanup();133 reject(new Error([134 'Failed to launch chrome!',135 stderr,...
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitFor(1000);6 await page.screenshot({path: 'google.png'});7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch({headless: false});12 const page = await browser.newPage();13 await page.waitFor(1000);14 await page.screenshot({path: 'google.png'});15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch({headless: false});20 const page = await browser.newPage();21 await page.waitFor(1000);22 await page.screenshot({path: 'google.png'});23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch({headless: false});28 const page = await browser.newPage();29 await page.waitFor(1000);30 await page.screenshot({path: 'google.png'});31 await browser.close();32})();33const puppeteer = require('puppeteer');34(async () => {35 const browser = await puppeteer.launch({headless: false});36 const page = await browser.newPage();37 await page.waitFor(1000);38 await page.screenshot({path: 'google.png'});39 await browser.close();40})();41const puppeteer = require('puppeteer');42(async () => {43 const browser = await puppeteer.launch({headless: false});
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({4 });5 const page = await browser.newPage();6 const wsEndpoint = await browser.waitForWSEndpoint();7 console.log(wsEndpoint);8 await browser.close();9})();10const puppeteer = require('puppeteer');11(async () => {12 const browser = await puppeteer.launch({13 });14 const page = await browser.newPage();15 console.log(target);16 await browser.close();17})();18const puppeteer = require('puppeteer');19(async () => {20 const browser = await puppeteer.launch({21 });22 const page = await browser.newPage();23 await page.waitFor(2000);24 await browser.close();25})();26const puppeteer = require('puppeteer');27(async () => {28 const browser = await puppeteer.launch({
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitFor(5000);6 await page.screenshot({path: 'example.png'});7 await browser.close();8})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitFor(3000);6 await page.screenshot({path: 'google.png'});7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch({headless: false});12 const page = await browser.newPage();13 await page.waitForNavigation();14 await page.screenshot({path: 'google.png'});15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch({headless: false});20 const page = await browser.newPage();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitFor(5000);6 await browser.close();7})();8const puppeteer = require('puppeteer');9(async () => {10 const browser = await puppeteer.launch({headless: false});11 await browser.waitForWSEndpoint();12 const page = await browser.newPage();13 await page.waitFor(5000);14 await browser.close();15})();16const puppeteer = require('puppeteer');17(async () => {18 const browser = await puppeteer.launch({headless: false});19 const page = await browser.newPage();20 await page.waitFor(5000);21 console.log(target);22 await browser.close();23})();24const puppeteer = require('puppeteer');25(async () => {26 const browser = await puppeteer.launch({headless: false});27 const page = await browser.newPage();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const waitForWSEndpoint = require('puppeteer-ws-endpoint');3(async () => {4 const browser = await puppeteer.launch();5 const wsEndpoint = await waitForWSEndpoint(browser);6 console.log(wsEndpoint);7 await browser.close();8})();9const puppeteer = require('puppeteer');10const waitForWSEndpoint = require('puppeteer-ws-endpoint');11(async () => {12 const browser = await puppeteer.launch();13 const wsEndpoint = await waitForWSEndpoint(browser);14 console.log(wsEndpoint);15 await browser.close();16})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.waitForWSEndpoint();6 await browser.close();7})();
Using AI Code Generation
1const puppeteer = require('puppeteer');2const { waitForWSEndpoint } = require('puppeteer-core/lib/Launcher');3(async () => {4 const browser = await puppeteer.launch();5 const wsEndpoint = await waitForWSEndpoint(browser);6 console.log(wsEndpoint);7 await browser.close();8})();9const puppeteer = require('puppeteer');10const { waitForWSEndpoint } = require('puppeteer-core/lib/Launcher');11(async () => {12 const browser = await puppeteer.launch();13 const wsEndpoint = await waitForWSEndpoint(browser);14 console.log(wsEndpoint);15 await browser.close();16})();17const puppeteer = require('puppeteer');18const { waitForWSEndpoint } = require('puppeteer-core/lib/Launcher');19(async () => {20 const browser = await puppeteer.launch();21 const wsEndpoint = await waitForWSEndpoint(browser);22 console.log(wsEndpoint);23 await browser.close();24})();25const puppeteer = require('puppeteer');26const { waitForWSEndpoint } = require('puppeteer-core/lib/Launcher');27(async () => {28 const browser = await puppeteer.launch();29 const wsEndpoint = await waitForWSEndpoint(browser);30 console.log(wsEndpoint);31 await browser.close();32})();33const puppeteer = require('puppeteer');34const { waitForWSEndpoint } = require('puppeteer-core/lib/Launcher');35(async () => {36 const browser = await puppeteer.launch();37 const wsEndpoint = await waitForWSEndpoint(browser);38 console.log(wsEndpoint);39 await browser.close();40})();41const puppeteer = require('puppeteer');42const { waitForWSEndpoint } = require('puppeteer-core/lib/Launcher');43(async () => {44 const browser = await puppeteer.launch();45 const wsEndpoint = await waitForWSEndpoint(browser);
Using AI Code Generation
1const puppeteer = require('puppeteer');2const cluster = await Cluster.launch({3 puppeteerOptions: {headless: false},4});5await cluster.task(async ({page, data: url}) => {6 await page.goto(url);7});8await cluster.idle();9await cluster.close();10const puppeteer = require('puppeteer');11const browser = await puppeteer.launch({headless: false});12const page = await browser.newPage();13await browser.close();14#### Cluster.launch(options)
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!