How to use evaluateOnNewDocument 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.

index.js

Source: index.js Github

copy
1var app = require('express')();
2const chrome = require('chrome-aws-lambda');
3const puppeteer = require('puppeteer-core');
4const axios = require("axios");
5const $ = require("cheerio");
6const fs = require("fs");
7
8app.get("/add", async function(req,res) {
9try {
10    const browser = await puppeteer.launch({
11        args: chrome.args,
12        executablePath: await chrome.executablePath,
13        headless: chrome.headless
14    });
15    const page = await browser.newPage();
16    page.on('dialog', async dialog => {
17    await dialog.accept();
18  });
19    const userAgent = 'Mozilla/5.0 (X11; Linux x86_64)' +
20  'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Safari/537.36';
21    await page.setUserAgent(userAgent);
22    await page.setViewport({
23      'width': 375,
24      'height': 812,
25      'deviceScaleFactor': 3,
26      'isMobile': true,
27      'hasTouch': true,
28      'isLandscape': false
29    });
30    await page.evaluateOnNewDocument(() => {
31  Object.defineProperty(navigator, 'webdriver', {
32    get: () => false,
33  });
34});
35    await page.evaluateOnNewDocument(() => {
36  // We can mock this in as much depth as we need for the test.
37  window.navigator.chrome = {
38    runtime: {},
39    // etc.
40  };
41});
42    await page.evaluateOnNewDocument(() => {
43  const originalQuery = window.navigator.permissions.query;
44  return window.navigator.permissions.query = (parameters) => (
45    parameters.name === 'notifications' ?
46      Promise.resolve({ state: Notification.permission }) :
47      originalQuery(parameters)
48  );
49});
50    await page.evaluateOnNewDocument(() => {
51  // Overwrite the `plugins` property to use a custom getter.
52  Object.defineProperty(navigator, 'plugins', {
53    // This just needs to have `length > 0` for the current test,
54    // but we could mock the plugins too if necessary.
55    get: () => [1, 2, 3, 4, 5],
56  });
57});
58    await page.evaluateOnNewDocument(() => {
59  // Overwrite the `plugins` property to use a custom getter.
60  Object.defineProperty(navigator, 'languages', {
61    get: () => ['en-US', 'en'],
62  });
63});
64    await page.goto("https://www.seedr.cc/");
65    await page.evaluate(function() {
66    login({username: "[email protected]",password: "Passsw0rd"});
67    });
68    await page.waitFor(1500);
69    var m = req.query.m || "magnet:?xt=urn:btih:dbf21fc9a28d7c292b5cd9462683a1e150d4e0e3";
70    await page.evaluate(function(m) {
71    add_link(m)
72    },m);
73    await page.waitFor(1000);
74    res.setHeader("Access-Control-Allow-Origin", "*");
75    res.end();
76    await browser.close();
77}
78catch(err) {
79    res.setHeader("Access-Control-Allow-Origin", "*");
80    res.status(502).send(err.message);
81   }
82})
83
84app.get("/delete", async function(req,res) {
85try {
86    const browser = await puppeteer.launch({
87        args: chrome.args,
88        executablePath: await chrome.executablePath,
89        headless: chrome.headless
90    });
91    const page = await browser.newPage();
92    page.on('dialog', async dialog => {
93    await dialog.accept();
94  });
95    const userAgent = 'Mozilla/5.0 (X11; Linux x86_64)' +
96  'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Safari/537.36';
97    await page.setUserAgent(userAgent);
98    await page.setViewport({
99      'width': 375,
100      'height': 812,
101      'deviceScaleFactor': 3,
102      'isMobile': true,
103      'hasTouch': true,
104      'isLandscape': false
105    });
106    await page.evaluateOnNewDocument(() => {
107  Object.defineProperty(navigator, 'webdriver', {
108    get: () => false,
109  });
110});
111    await page.evaluateOnNewDocument(() => {
112  // We can mock this in as much depth as we need for the test.
113  window.navigator.chrome = {
114    runtime: {},
115    // etc.
116  };
117});
118    await page.evaluateOnNewDocument(() => {
119  const originalQuery = window.navigator.permissions.query;
120  return window.navigator.permissions.query = (parameters) => (
121    parameters.name === 'notifications' ?
122      Promise.resolve({ state: Notification.permission }) :
123      originalQuery(parameters)
124  );
125});
126    await page.evaluateOnNewDocument(() => {
127  // Overwrite the `plugins` property to use a custom getter.
128  Object.defineProperty(navigator, 'plugins', {
129    // This just needs to have `length > 0` for the current test,
130    // but we could mock the plugins too if necessary.
131    get: () => [1, 2, 3, 4, 5],
132  });
133});
134    await page.evaluateOnNewDocument(() => {
135  // Overwrite the `plugins` property to use a custom getter.
136  Object.defineProperty(navigator, 'languages', {
137    get: () => ['en-US', 'en'],
138  });
139});
140    await page.goto("https://www.seedr.cc/");
141    await page.evaluate(function() {
142    login({username: "[email protected]",password: "Passsw0rd"});
143    });
144    await page.waitForSelector("#first-folder", { timeout: 5000 });
145    await page.click("#first-folder");
146    await page.keyboard.press('Delete');
147    await page.waitFor(750);
148    res.setHeader("Access-Control-Allow-Origin", "*");
149    res.end();
150    await browser.close();
151}
152catch(err) {
153    res.setHeader("Access-Control-Allow-Origin", "*");
154    res.end();
155   }
156})
157
158
159app.get("/get", async function(req,res) {
160try {
161    const browser = await puppeteer.launch({
162        args: chrome.args,
163        executablePath: await chrome.executablePath,
164        headless: chrome.headless
165    });
166    const page = await browser.newPage();
167    const userAgent = 'Mozilla/5.0 (X11; Linux x86_64)' +
168  'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Safari/537.36';
169    await page.setUserAgent(userAgent);
170    await page.setViewport({
171      'width': 375,
172      'height': 812,
173      'deviceScaleFactor': 3,
174      'isMobile': true,
175      'hasTouch': true,
176      'isLandscape': false
177    });
178    await page.evaluateOnNewDocument(() => {
179  Object.defineProperty(navigator, 'webdriver', {
180    get: () => false,
181  });
182});
183    await page.evaluateOnNewDocument(() => {
184  // We can mock this in as much depth as we need for the test.
185  window.navigator.chrome = {
186    runtime: {},
187    // etc.
188  };
189});
190    await page.evaluateOnNewDocument(() => {
191  const originalQuery = window.navigator.permissions.query;
192  return window.navigator.permissions.query = (parameters) => (
193    parameters.name === 'notifications' ?
194      Promise.resolve({ state: Notification.permission }) :
195      originalQuery(parameters)
196  );
197});
198    await page.evaluateOnNewDocument(() => {
199  // Overwrite the `plugins` property to use a custom getter.
200  Object.defineProperty(navigator, 'plugins', {
201    // This just needs to have `length > 0` for the current test,
202    // but we could mock the plugins too if necessary.
203    get: () => [1, 2, 3, 4, 5],
204  });
205});
206    await page.evaluateOnNewDocument(() => {
207  // Overwrite the `plugins` property to use a custom getter.
208  Object.defineProperty(navigator, 'languages', {
209    get: () => ['en-US', 'en'],
210  });
211});
212    await page.goto("https://www.seedr.cc/");
213    await page.evaluate(function() {
214    login({username: "[email protected]",password: "Passsw0rd"});
215    });
216    await page.waitForSelector("#first-folder");
217    var id = await page.evaluate(function() {return document.querySelector("#first-folder").getAttribute("folder_id");});
218    res.setHeader("Access-Control-Allow-Origin", "*");
219    res.end(req.baseUrl+'/search?id='+id);
220    await browser.close();
221}
222catch(err) {
223    res.redirect(301,req.baseUrl+"/get");
224   }
225})
226
227app.get("/search", async function(req,res) {
228try {
229    const browser = await puppeteer.launch({
230        args: chrome.args,
231        executablePath: await chrome.executablePath,
232        headless: chrome.headless
233    });
234    const page = await browser.newPage();
235    const userAgent = 'Mozilla/5.0 (X11; Linux x86_64)' +
236  'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.39 Safari/537.36';
237    await page.setUserAgent(userAgent);
238    await page.setViewport({
239      'width': 375,
240      'height': 812,
241      'deviceScaleFactor': 3,
242      'isMobile': true,
243      'hasTouch': true,
244      'isLandscape': false
245    });
246    await page.evaluateOnNewDocument(() => {
247  Object.defineProperty(navigator, 'webdriver', {
248    get: () => false,
249  });
250});
251    await page.evaluateOnNewDocument(() => {
252  // We can mock this in as much depth as we need for the test.
253  window.navigator.chrome = {
254    runtime: {},
255    // etc.
256  };
257});
258    await page.evaluateOnNewDocument(() => {
259  const originalQuery = window.navigator.permissions.query;
260  return window.navigator.permissions.query = (parameters) => (
261    parameters.name === 'notifications' ?
262      Promise.resolve({ state: Notification.permission }) :
263      originalQuery(parameters)
264  );
265});
266    await page.evaluateOnNewDocument(() => {
267  // Overwrite the `plugins` property to use a custom getter.
268  Object.defineProperty(navigator, 'plugins', {
269    // This just needs to have `length > 0` for the current test,
270    // but we could mock the plugins too if necessary.
271    get: () => [1, 2, 3, 4, 5],
272  });
273});
274    await page.evaluateOnNewDocument(() => {
275  // Overwrite the `plugins` property to use a custom getter.
276  Object.defineProperty(navigator, 'languages', {
277    get: () => ['en-US', 'en'],
278  });
279});
280    await page.goto("https://www.seedr.cc/files/"+req.query.id);
281    await page.evaluate(function() {
282    login({username: "[email protected]",password: "Passsw0rd"});
283    });
284    await page.waitForSelector(".video-icon-bg");
285    await page.click('.video-icon-bg', {button : 'right'}); 
286    await page.waitFor(600)
287    var url = await page.evaluate(function() {document.querySelector("div.context-menu-item:nth-child(2)").click();return document.querySelector('.alert-box').innerHTML.split(" ")[1]})
288    res.setHeader("Access-Control-Allow-Origin", "*");
289    res.end(url.split("&").join("&"));
290    await browser.close();
291}
292catch(err) {
293    res.setHeader("Access-Control-Allow-Origin", "*");
294    res.status(502).send(err.message);
295   }
296})
297
298app.listen(process.env.PORT);
299
Full Screen

stealth.js

Source: stealth.js Github

copy
1async function hideHeadless(page) {
2  // Pass the User-Agent Test.
3  const userAgent = `Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36`;
4  await page.setUserAgent(userAgent);
5
6  // Pass the Webdriver Test.
7  await page.evaluateOnNewDocument(() => {
8    Object.defineProperty(navigator, "webdriver", {
9      get: () => false,
10    });
11  });
12
13  // Pass the Chrome Test.
14  await page.evaluateOnNewDocument(() => {
15    // We can mock this in as much depth as we need for the test.
16    window.navigator.chrome = {
17      runtime: {},
18      // etc.
19    };
20  });
21
22  // Pass the Permissions Test.
23  await page.evaluateOnNewDocument(() => {
24    const originalQuery = window.navigator.permissions.query;
25    return (window.navigator.permissions.query = (parameters) =>
26      parameters.name === "notifications"
27        ? Promise.resolve({ state: Notification.permission })
28        : originalQuery(parameters));
29  });
30
31  // Pass the Plugins Length Test.
32  await page.evaluateOnNewDocument(() => {
33    // Overwrite the `plugins` property to use a custom getter.
34    Object.defineProperty(navigator, "plugins", {
35      // This just needs to have `length > 0` for the current test,
36      // but we could mock the plugins too if necessary.
37      get: () => [1, 2, 3, 4, 5],
38    });
39  });
40
41  // Pass the Languages Test.
42  await page.evaluateOnNewDocument(() => {
43    // Overwrite the `plugins` property to use a custom getter.
44    Object.defineProperty(navigator, "languages", {
45      get: () => ["en-US", "en"],
46    });
47  });
48}
49
50module.exports = {
51  hideHeadless,
52};
53
Full Screen

preparePageForTests.js

Source: preparePageForTests.js Github

copy
1const preparePageForTests = async (page) => {
2  // Pass the User-Agent Test.
3/*
4  const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
5  await page.setUserAgent(userAgent);
6*/
7  // To ensure Amazon doesn't detect it as a Bot
8  await page.setExtraHTTPHeaders({
9    "Accept-Language": "en-US,en;q=0.9",
10  });
11
12  // Pass the Webdriver Test.
13  await page.evaluateOnNewDocument(() => {
14    Object.defineProperty(navigator, "webdriver", {
15      get: () => false,
16    });
17  });
18  // await page.setViewport({ width: 1200, height: 2000 });
19
20  // Pass the Chrome Test.
21  await page.evaluateOnNewDocument(() => {
22    // We can mock this in as much depth as we need for the test.
23    window.navigator.chrome = {
24      runtime: {},
25      // etc.
26    };
27  });
28
29  await page.setDefaultNavigationTimeout(0);
30
31  // Pass the Permissions Test.
32  await page.evaluateOnNewDocument(() => {
33    const originalQuery = window.navigator.permissions.query;
34    return (window.navigator.permissions.query = (parameters) =>
35      parameters.name === "notifications"
36        ? Promise.resolve({ state: Notification.permission })
37        : originalQuery(parameters));
38  });
39
40  // Pass the Plugins Length Test.
41  await page.evaluateOnNewDocument(() => {
42    // Overwrite the `plugins` property to use a custom getter.
43    Object.defineProperty(navigator, "plugins", {
44      // This just needs to have `length > 0` for the current test,
45      // but we could mock the plugins too if necessary.
46      get: () => [1, 2, 3, 4, 5],
47    });
48  });
49
50  // Pass the Languages Test.
51  await page.evaluateOnNewDocument(() => {
52    // Overwrite the `plugins` property to use a custom getter.
53    Object.defineProperty(navigator, "languages", {
54      get: () => ["en-US", "en"],
55    });
56  });
57};
58module.exports = preparePageForTests;
59
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)