Best JavaScript code snippet using playwright-internal
pdf.js
Source:pdf.js
1/*2 * pdf function3 *4 * Example invocation:5 *6 * pdf({7 * page: await browser.newPage(),8 * context: {9 * url: 'https://example.com',10 * html: '<div>example</div>11 * options: {12 * ...13 * see https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagepdfoptions for available options14 * }15 * },16 * });17 *18 * @param args - object - An object with a puppeteer page object, and context.19 * @param args.page - object - Puppeteer's page object (from await browser.newPage)20 * @param args.context - object - An object of parameters that the function is called with. See src/schemas.ts21 */22const buildPages = async (page, opts = {}) => {23 const pdftk = require('node-pdftk');24 const pageBuffers = [];25 let complete = false;26 let pageCount = 1;27 // If ranges are specified, don't render them all28 if (opts.pageRanges) {29 return page.pdf(opts);30 }31 while (!complete) {32 try {33 const buffer = await page.pdf({34 ...opts,35 pageRanges: pageCount.toString(),36 });37 pageBuffers.push(buffer);38 pageCount = pageCount + 1;39 } catch(error) {40 if (error.message && error.message.includes('Page range exceeds page count')) {41 complete = true;42 } else {43 throw error;44 }45 }46 }47 return pdftk48 .input(pageBuffers)49 .cat()50 .compress()51 .output();52};53module.exports = async function pdf({ page, context }) {54 const {55 authenticate = null,56 addScriptTag = [],57 addStyleTag = [],58 cookies = [],59 emulateMedia,60 viewport,61 html,62 options,63 url = null,64 rotate = null,65 safeMode,66 gotoOptions,67 rejectRequestPattern = [],68 requestInterceptors = [],69 setExtraHTTPHeaders,70 setJavaScriptEnabled = null,71 userAgent = null,72 waitFor,73 } = context;74 if (authenticate) {75 await page.authenticate(authenticate);76 }77 if (setExtraHTTPHeaders) {78 await page.setExtraHTTPHeaders(setExtraHTTPHeaders);79 }80 if (setJavaScriptEnabled !== null) {81 await page.setJavaScriptEnabled(setJavaScriptEnabled);82 }83 if (rejectRequestPattern.length || requestInterceptors.length) {84 await page.setRequestInterception(true);85 page.on('request', (req) => {86 if (rejectRequestPattern.find((pattern) => req.url().match(pattern))) {87 return req.abort();88 }89 const interceptor = requestInterceptors90 .find(r => req.url().match(r.pattern));91 if (interceptor) {92 return req.respond(interceptor.response);93 }94 return req.continue();95 });96 }97 if (emulateMedia) {98 // Run the appropriate emulateMedia method, making sure it's bound properly to the page object99 // @todo remove when support drops for 3.x.x100 const emulateMediaFn = (page.emulateMedia || page.emulateMediaType).bind(page);101 await emulateMediaFn(emulateMedia);102 }103 if (cookies.length) {104 await page.setCookie(...cookies);105 }106 if (viewport) {107 await page.setViewport(viewport);108 }109 if (userAgent) {110 await page.setUserAgent(userAgent);111 }112 if (url !== null) {113 await page.goto(url, gotoOptions);114 } else {115 // Whilst there is no way of waiting for all requests to finish with setContent,116 // you can simulate a webrequest this way117 // see issue for more details: https://github.com/GoogleChrome/puppeteer/issues/728118 await page.setRequestInterception(true);119 page.once('request', request => {120 request.respond({ body: html });121 page.on('request', request => request.continue());122 });123 await page.goto('http://localhost', gotoOptions);124 }125 if (addStyleTag.length) {126 for (tag in addStyleTag) {127 await page.addStyleTag(addStyleTag[tag]);128 }129 }130 if (addScriptTag.length) {131 for (script in addScriptTag) {132 await page.addScriptTag(addScriptTag[script]);133 }134 }135 if (waitFor) {136 if (typeof waitFor === 'string') {137 const isSelector = await page.evaluate((s) => {138 try { document.createDocumentFragment().querySelector(s); }139 catch (e) { return false; }140 return true;141 }, waitFor);142 await (isSelector ? page.waitFor(waitFor) : page.evaluate(`(${waitFor})()`));143 } else {144 await page.waitFor(waitFor);145 }146 }147 let data = safeMode ?148 await buildPages(page, options) :149 await page.pdf(options);150 if (rotate) {151 const pdftk = require('node-pdftk');152 const rotateValue = rotate === 90 ?153 '1-endright' :154 rotate === -90 ?155 '1-endleft' :156 rotate === 180 ?157 '1-enddown' :158 '';159 data = await pdftk160 .input(data)161 .rotate(rotateValue)162 .output();163 }164 return {165 data,166 type: 'pdf',167 };...
index.js
Source:index.js
...98 break;99 case 'pdf':100 let { emulateMedia } = options;101 if (emulateMedia !== null && emulateMedia !== undefined) {102 await page._chromePage.emulateMedia(emulateMedia);103 delete options.emulateMedia;104 }105 buffer = await page._chromePage.pdf(options);106 break;107 default:108 buffer = await page._chromePage.screenshot(options);109 break;110 }111 return isString(filepath) ? filepath : buffer;112 }113 async unloadPage(page, ...args) {114 await page._chromePage.close();115 return true;116 }...
PDFGenerator.js
Source:PDFGenerator.js
...22 console.log(this.transferencia);23 const browser = await puppeteer.launch(CONFIG_PDFGENERATOR.launcher);24 const page = await browser.newPage();25 await page.setContent(template);26 await page.emulateMedia(CONFIG_PDFGENERATOR.emulateMedia);27 const PDF = await page.pdf(CONFIG_PDFGENERATOR.options);28 await browser.close();29 return PDF;30 }31 async getPDFTrans() {32 let plantilla;33 if (this.transferencia.estatus_stp != "Exito") {34 plantilla = CONFIG_PDFGENERATOR.pathTemplateError;35 } else {36 plantilla = CONFIG_PDFGENERATOR.pathTemplateExito;37 }38 const templateHTML = fs.readFileSync(39 path.join(process.cwd(), plantilla),40 "utf-8"41 );42 const template = await handlebars.compile(templateHTML)({43 ...this.transferencia._doc,44 });45 const browser = await puppeteer.launch(CONFIG_PDFGENERATOR.launcher);46 const page = await browser.newPage();47 await page.setContent(template);48 await page.emulateMedia(CONFIG_PDFGENERATOR.emulateMedia);49 const PDF = await page.pdf(CONFIG_PDFGENERATOR.options);50 await browser.close();51 return PDF;52 }53 async getPDFDispersion() {54 const plantilla = CONFIG_PDFGENERATOR.pathTemplateExitoD;55 const templateHTML = fs.readFileSync(56 path.join(process.cwd(), plantilla),57 "utf-8"58 );59 const { fecha } = DateGenerator.getDateAndHour(60 this.transferencia.fechaSubida61 );62 // Creamos helper en Handlebars para poder realizar63 // suma en la plantilla (sum)64 handlebars.registerHelper("sum", (value) => {65 return parseInt(value) + 1;66 });67 handlebars.registerHelper("GetTipoCuenta", (value) => {68 if (value == 3) return "TDD";69 if (value == 40) return "Clabe Inter";70 });71 const Total = this.transferencia.idTransferencia.reduce(72 (accumulator, current) =>73 parseFloat(parseFloat(accumulator) + parseFloat(current.monto)).toFixed(74 275 ),76 077 );78 const template = await handlebars.compile(templateHTML)({79 ...this.transferencia,80 tiposCuentas: TIPOS_CUENTAS,81 Total,82 fecha,83 });84 const browser = await puppeteer.launch(CONFIG_PDFGENERATOR.launcher);85 const page = await browser.newPage();86 await page.setContent(template);87 await page.emulateMedia(CONFIG_PDFGENERATOR.emulateMedia);88 const PDF = await page.pdf(CONFIG_PDFGENERATOR.options);89 await browser.close();90 return PDF;91 }92}...
render.js
Source:render.js
...26 pathToStatic,27 });28 if (renderProcessingErrors.length)29 logger.warn("anchors processing errors", renderProcessingErrors);30 await page.emulateMedia(emulateMedia);31 await page.pdf({32 ...pdfOptions,33 path: path.resolve(pathToPublic),34 });35 return await browser.close();36 } catch (e) {37 await browser.close();38 throw e;39 }40};41const htmlToPdf = ({42 mainMdFilename,43 pathToStatic,44 pathToPublic,...
pass-commands.test.js
Source:pass-commands.test.js
...15 expect(window.innerHeight).to.equal(1600);16 expect(window.innerWidth).to.equal(1400);17});18it('can emulate print media type', async () => {19 await emulateMedia({ media: 'print' });20 expect(matchMedia('print').matches).to.be.true;21 await emulateMedia({ media: 'screen' });22 expect(matchMedia('screen').matches).to.be.true;23});24it('can emulate color scheme', async () => {25 await emulateMedia({ colorScheme: 'dark' });26 expect(matchMedia('(prefers-color-scheme: dark)').matches).to.be.true;27 await emulateMedia({ colorScheme: 'light' });28 expect(matchMedia('(prefers-color-scheme: light)').matches).to.be.true;...
dark-mode.js
Source:dark-mode.js
...4 const page = await browser.newPage();5 await page.goto(6 'https://googlechromelabs.github.io/dark-mode-toggle/demo/index.html',7 );8 await page.emulateMedia({ colorScheme: 'light' });9 await page.waitForTimeout(200);10 await page.screenshot({11 path: 'screenshots/light.jpg',12 type: 'jpeg',13 omitBackground: true,14 });15 await page.emulateMedia({ colorScheme: 'dark' });16 await page.waitForTimeout(200);17 await page.screenshot({18 path: 'screenshots/dark.jpg',19 type: 'jpeg',20 omitBackground: true,21 });22 await browser.close();...
browser-test.js
Source:browser-test.js
1import { emulateMedia } from '../../browser/commands.mjs';2import { expect } from '../chai.js';3it('can emulate print media type', async () => {4 await emulateMedia({ media: 'print' });5 expect(matchMedia('print').matches).to.be.true;6 await emulateMedia({ media: 'screen' });7 expect(matchMedia('screen').matches).to.be.true;8});9it.only('can emulate color scheme', async () => {10 await emulateMedia({ colorScheme: 'dark' });11 expect(matchMedia('(prefers-color-scheme: dark)').matches).to.be.true;12 await emulateMedia({ colorScheme: 'light' });13 expect(matchMedia('(prefers-color-scheme: light)').matches).to.be.true;...
prefers-reduced-motion-test.js
Source:prefers-reduced-motion-test.js
1import { emulateMedia } from '../../browser/commands.mjs';2import { expect } from '../chai.js';3it('can emulate reduced motion', async () => {4 await emulateMedia({ reducedMotion: 'reduce' });5 expect(matchMedia('(prefers-reduced-motion: reduce)').matches).to.be.true;6 await emulateMedia({ reducedMotion: 'no-preference' });7 expect(matchMedia('(prefers-reduced-motion: no-preference)').matches).to.be.true;...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 await page.emulateMedia({6 });7 await page.screenshot({ path: `dark.png` });8 await page.emulateMedia({9 });10 await page.screenshot({ path: `light.png` });11 await browser.close();12})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.emulateMedia({7 });8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext({5 });6 await context._setEmulatedMedia({media: 'screen', colorScheme: 'dark', reducedMotion: 'reduce'});7 const page = await context.newPage();8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();11const {chromium} = require('playwright');12(async () => {13 const browser = await chromium.launch({14 });15 const page = await browser.newPage();16 await page.screenshot({ path: `example.png` });17 await browser.close();18})();19const {chromium} = require('playwright');20(async () => {21 const browser = await chromium.launch({22 userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'23 });
Using AI Code Generation
1const { chromium } = require("playwright");2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext({5 "Mozilla/5.0 (Linux; Android 9; ONEPLUS A6013) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.101 Mobile Safari/537.36",6 });7 const page = await context.newPage();8 await page.emulateMedia({ media: "screen", colorScheme: "dark" });9 await page.screenshot({ path: "google.png" });10 await browser.close();11})();12const { chromium } = require("playwright");13(async () => {14 const browser = await chromium.launch({ headless: false });15 const context = await browser.newContext();16 const page = await context.newPage();17 await page.emulate({18 viewport: {19 },20 "Mozilla/5.0 (Linux; Android 9; ONEPLUS A6013) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.101 Mobile Safari/537.36",21 });22 await page.screenshot({ path: "google.png" });23 await browser.close();24})();25const { chromium } = require("playwright");26(async () => {27 const browser = await chromium.launch({ headless: false });28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.setGeolocation({ latitude: 51.50853, longitude: -0.12574 });31 await page.screenshot({ path: "google.png" });32 await browser.close();33})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.emulateMedia('screen');7 await page.screenshot({ path: `example.png` });8 await browser.close();9})();10const { chromium } = require('playwright');11(async () => {12 const browser = await chromium.launch();13 const context = await browser.newContext();14 const page = await context.newPage();15 await page.emulateMedia('print');16 await page.screenshot({ path: `example.png` });17 await browser.close();18})();19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.emulateMedia('screen');25 await page.screenshot({ path: `example.png` });26 await page.emulateMedia('print');27 await page.screenshot({ path: `example2.png` });28 await browser.close();29})();30const { chromium } = require('playwright');31(async () => {32 const browser = await chromium.launch();33 const context = await browser.newContext();34 const page = await context.newPage();35 await page.emulateMedia('screen');36 await page.screenshot({ path: `example.png` });37 await page.emulateMedia('screen');38 await page.screenshot({ path: `example2.png` });39 await browser.close();40})();41const { chromium } = require('playwright');42(async () => {43 const browser = await chromium.launch();44 const context = await browser.newContext();45 const page = await context.newPage();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext({5 userAgent: 'Mozilla/5.0 (Linux; Android 9; Pixel 2 XL) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Mobile Safari/537.36',6 viewport: {7 },8 });9 const page = await context.newPage();10 await page.screenshot({ path: `example.png` });11 await browser.close();12})();
Using AI Code Generation
1const playwright = require("playwright");2(async () => {3 const browser = await playwright["chromium"].launch();4 const page = await browser.newPage();5 await page.emulateMedia({6 });7 await page.screenshot({ path: "dark.png" });8 await browser.close();9})();10- [x] **`page.emulateMedia(options)`**11- [x] **`page.emulate(options)`**12- [x] **`page.evaluate(expression[, arg1, arg2, ...])`**13- [x] **`page.evaluateHandle(expression[, arg1, arg2, ...])`**14- [x] **`page.exposeBinding(name, callback[, options])`**15- [x] **`page.fill(selector, value[, options])`**16- [x] **`page.focus(selector[, options])`**17- [x] **`page.frames()`**18- [x] **`page.goBack([options])`**19- [x] **`page.goForward([options])`**20- [x] **`page.goto(url[, options])`**21- [x] **`page.hover(selector[, options])`**22- [x] **`page.injectFile(file)`**23- [x] **`page.isClosed()`**24- [x] **`page.mainFrame()`**25- [x] **`page.off(event, handler)`**26- [x] **`page.on(event, handler)`**27- [x] **`page.once(event, handler)`**28- [x] **`page.opener()`**29- [x] **`page.pdf([options])`**30- [x] **`page.querySelector(selector)`**31- [x] **`page.querySelectorAll(selector)`**32- [x] **`page.route(url, handler)`**33- [x] **`page.route(url, handler)`**34- [x] **`page.route(url, handler)`**
Using AI Code Generation
1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext({5 userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1',6 });7 const page = await context.newPage();8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();11const {chromium} = require('playwright');12(async () => {13 const browser = await chromium.launch({ headless: false });14 const context = await browser.newContext({15 userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.3 Mobile/15E148 Safari/604.1',16 });17 const page = await context.newPage();18 await page.emulateMedia({ media: 'screen', colorScheme: 'dark', reducedMotion: 'reduce' });19 await page.screenshot({ path: `example.png` });20 await browser.close();21})();22const {chromium} = require('playwright');23(async () => {24 const browser = await chromium.launch({ headless: false });25 const context = await browser.newContext({26 viewport: { width: 375, height: 812 },27 userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_4_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.emulateMedia({7 });8 await page.screenshot({ path: `example.png` });9 await browser.close();10})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!