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

inboxonly.js

Source: inboxonly.js Github

copy
1const puppeteer = require("puppeteer-extra");
2const EventEmitter = require("events");
3const StealthPlugin = require("puppeteer-extra-plugin-stealth");
4// const utils = require("./utils.js");
5var fs = require("fs");
6
7var logger = require("tracer").console({
8  transport: function (data) {
9    console.log(data.output);
10    fs.appendFile("./file.log", data.rawoutput + "\n", (err) => {
11      if (err) throw err;
12    });
13  },
14});
15// const proxy_check = require('proxy-check');
16
17require("puppeteer-extra-plugin-stealth/evasions/defaultArgs");
18require("puppeteer-extra-plugin-stealth/evasions/chrome.app");
19require("puppeteer-extra-plugin-stealth/evasions/chrome.csi");
20require("puppeteer-extra-plugin-stealth/evasions/chrome.loadTimes");
21require("puppeteer-extra-plugin-stealth/evasions/chrome.runtime");
22require("puppeteer-extra-plugin-stealth/evasions/iframe.contentWindow");
23require("puppeteer-extra-plugin-stealth/evasions/media.codecs");
24require("puppeteer-extra-plugin-stealth/evasions/navigator.hardwareConcurrency");
25require("puppeteer-extra-plugin-stealth/evasions/navigator.languages");
26require("puppeteer-extra-plugin-stealth/evasions/navigator.permissions");
27require("puppeteer-extra-plugin-stealth/evasions/navigator.plugins");
28require("puppeteer-extra-plugin-stealth/evasions/navigator.vendor");
29require("puppeteer-extra-plugin-stealth/evasions/navigator.webdriver");
30require("puppeteer-extra-plugin-stealth/evasions/sourceurl");
31require("puppeteer-extra-plugin-stealth/evasions/user-agent-override");
32require("puppeteer-extra-plugin-stealth/evasions/webgl.vendor");
33require("puppeteer-extra-plugin-stealth/evasions/window.outerdimensions");
34require("dotenv").config();
35puppeteer.use(StealthPlugin());
36const emitter = new EventEmitter();
37
38emitter.setMaxListeners(1000);
39
40var categorizeSeed = {};
41const gmailProcess = async (emailJson) => {
42  for (let i = 0; i < emailJson.length; i++) {
43    // `email_of_${i.seedNo}_${i.browserNo}`
44    if (!categorizeSeed[emailJson[i].seedNo]) {
45      categorizeSeed[emailJson[i].seedNo] = [];
46    }
47    categorizeSeed[emailJson[i].seedNo].push(emailJson[i]);
48  }
49  // console.log("categorizeSeed >>>>>>>>>>", categorizeSeed);
50  if (!Object.keys(categorizeSeed).length) return;
51
52  let seedLen = Object.keys(categorizeSeed).length;
53  for (let index = 1; index <= seedLen; index++) {
54    if (categorizeSeed[index]) {
55      const params = { seedNo: "above seed", browserNumber: index + 1 };
56      // await utils.checkCpuAndDelay(params);
57      Mainflow(categorizeSeed[index], index);
58    }
59  }
60};
61
62async function Mainflow(browsersArr, browserNo) {
63  try {
64    for (let index = 0; index <= browsersArr.length; index++) {
65      const params = { seedNo: index + 1, browserNumber: browserNo };
66      // await utils.checkCpuAndDelay(params);
67      if (browsersArr.length == index) {
68        index = 0;
69      }
70      const item = browsersArr[index];
71
72      const sessionData = `${browserNo}`;
73
74      const args = [
75        `--proxy-server=http://${item.proxyIP.trim()}:${item.proxyPort.trim()}`,
76        "--no-sandbox",
77        "--disable-setuid-sandbox",
78        "--disable-infobars",
79        "--window-position=0,0",
80        "--ignore-certifcate-errors",
81        "--ignore-certifcate-errors-spki-list",
82        "--use-gl=egl",
83        "--disable-background-timer-throttling",
84        "--enable-automation",
85        "--disable-renderer-backgrounding",
86        "--disable-backgrounding-occluded-windows",
87        "--disable-ipc-flooding-protection",
88      ];
89
90      const lauchoptions = {
91        executablePath:
92          "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
93        args,
94        userDataDir: sessionData,
95        headless: false,
96        devtools: false,
97        ignoreHTTPSErrors: true,
98        // slowMo: 100
99      };
100
101      const width = 1024;
102      const height = 1600;
103
104      const browser = await puppeteer.launch(lauchoptions, {
105        defaultViewport: { width: width, height: height },
106      });
107      //  const page = await browser.newPage();
108      const page = (await browser.pages())[0];
109      page.setDefaultNavigationTimeout(90000);
110      // await utils.checkCpuAndDelay(params);
111
112      // try {
113      //   await page.setDefaultNavigationTimeout(1000 * 60 * 3);
114      // } catch (ex) {
115      //   console.error(ex);
116      //   //    await browser.close()
117      // }
118      await page.bringToFront();
119      await page.authenticate({
120        username: item.proxyUsername,
121        password: item.proxyPassword,
122      });
123      await page.bringToFront();
124
125      for (let i = 0; i <= 11; i++) {
126        await sleep(1000);
127        if (i == 11) {
128          i = 0;
129        }
130        https://mail.google.com/mail/u/1/#search/in%3Ainbox+welcome+OR+liberty/FMfcgzGmthmXxmntkRPvnCnWBNrlpkTn
131        await page.bringToFront();
132        await Promise.all([page.keyboard.press("Enter")]);
133        await Promise.all([page.keyboard.press("Enter")]);
134        try {
135          
136          // await page.goto(
137          //   `https://mail.google.com/mail/u/${i}/#inbox`,
138          //     pressenter(page,i),
139          //   // https://mail.google.com/mail/u/${i}/h/1skwmxqy8dsdn/?&
140          //   {
141              
142          //     waitUntil:"domcontentloaded",
143              
144          //     timeout: 1* 1000* 60,
145          //   },
146            
147          // );
148          await sleep(9000)
149
150          await page.goto(`https://mail.google.com/mail/u/${i}/#inbox`, {waituntil: "domcontentloaded"});
151
152          // //Find the iFrame with the URL http://www.allwebco-templates.com/support/
153          // const frame = await page.frames().find(f => f.url() === `https://mail.google.com/mail/u/${i-1}/#search/in%3Ainbox+welcome+OR+liberty/FMfcgzGmthmXxmntkRPvnCnWBNrlpkTn`);
154          // if(!frame){
155          //   console.log("iFrame not found with the specified url");
156            
157          // }
158          // await Promise.all([page.keyboard.press("Enter")]);
159          // await Promise.all([page.keyboard.press("Enter")]);
160          
161        } catch (ex) {
162         
163          console.error(ex);
164
165          // await browser.close()
166        }
167
168        await page.bringToFront();
169        if ((await page.$("#main-message > h1 > span")) !== null) {
170          let proxyreconnect = await eval(
171            page,
172            `() => document.querySelector('#main-message > h1 > span').innerText == 'No internet'`
173          );
174          if (proxyreconnect == true) {
175            await page.reload({
176              waitUntil: ["networkidle0", "domcontentloaded"],
177            });
178          }
179        }
180        await Promise.all([page.keyboard.press("Enter")]);
181        await Promise.all([page.keyboard.press("Enter")]);
182        await page.bringToFront();
183
184        // if(i == 0){
185        //   let pages3 = await browser.pages();
186        // await pages3[0].close();
187        // }
188        // for (let j = 0; i <= 2; j++) {
189        if ((await page.$("#maia-main > form > p > input")) !== null) {
190          await page.click("#maia-main > form > p > input");
191        }
192        await Promise.all([page.keyboard.press("Enter")]);
193        await page.bringToFront();
194        await Promise.all([page.keyboard.press("Enter")]);
195        await Promise.all([page.keyboard.press("Enter")]);
196        const searchmail = '[aria-label="Search mail"]';
197        await page.waitForSelector(searchmail);
198        await page.click(searchmail);
199        await page.bringToFront();
200        let pages13 = await browser.pages();
201        if (pages13[1]) {
202          await pages13[1].close();
203        }
204        if (pages13[2]) {
205          await pages13[2].close();
206        }
207        if (pages13[3]) {
208          await pages13[3].close();
209        }
210        await Promise.all([page.keyboard.press("Enter")]);
211        await Promise.all([page.keyboard.press("Enter")]);
212        // await searchmail.click({ clickCount: 3 });
213        await page.type(searchmail, `in:spam `);
214        await Promise.all([page.keyboard.press("Enter")]);
215        await page.bringToFront();
216        await sleep(20000);
217
218        const checkPrice = await page.$x(
219          "//td[contains(text(), 'Hooray, no spam here!')]"
220        );
221        console.log(checkPrice.length);
222        
223        if (checkPrice.length == 0) {
224          const click1 = await page.$x(
225            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[1]/td[2]"
226          );
227          await page.bringToFront();
228          // "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[3]/div[5]/div[2]/div/table/tbody/tr[1]/td[2]"
229          if (click1.length) {
230            await click1[0].click();
231          }
232          const click2 = await page.$x(
233            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[2]/td[2]"
234          );
235          if (click2.length) {
236            await click2[0].click();
237          }
238          const click3 = await page.$x(
239            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[3]/td[2]"
240          );
241          if (click3.length) {
242            await click3[0].click();
243          }
244          const click4 = await page.$x(
245            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[4]/td[2]"
246          );
247          if (click4.length) {
248            await click4[0].click();
249          }
250          const click5 = await page.$x(
251            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[5]/td[2]"
252          );
253          if (click5.length) {
254            await click5[0].click();
255          }
256          const click6 = await page.$x(
257            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[6]/td[2]"
258          );
259          // "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[3]/div[5]/div[2]/div/table/tbody/tr[1]/td[2]"
260          if (click6.length) {
261            await click6[0].click();
262          }
263          const click7 = await page.$x(
264            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[7]/td[2]"
265          );
266          if (click7.length) {
267            await click7[0].click();
268          }
269          const click8 = await page.$x(
270            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[8]/td[2]"
271          );
272          if (click8.length) {
273            await click8[0].click();
274          }
275          const click9 = await page.$x(
276            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[9]/td[2]"
277          );
278          if (click9.length) {
279            await click9[0].click();
280          }
281          const click10 = await page.$x(
282            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[4]/div[2]/div/table/tbody/tr[10]/td[2]"
283          );
284          if (click10.length) {
285            await click10[0].click();
286          }
287          await page.bringToFront();
288          await sleep(2000);
289          let notspamcheck = await eval(
290            page,
291            `() => document.getElementsByClassName('Bn')[1].innerText == 'Not spam'`
292          );
293          await page.bringToFront();
294          await sleep(3000);
295          // let notspamclick = await eval(page, `() => document.getElementsByClassName('Bn')[1]`);
296          if (notspamcheck == true) {
297            await page.click(
298              "div.D.E.G-atb.PY > div.nH.aqK > div.Cq.aqL > div > div > div:nth-child(3) > div > div"
299            );
300          }
301          await page.bringToFront();
302          await sleep(15000)
303        }
304        await page.bringToFront();
305        await page.goto(
306          `https://mail.google.com/mail/u/${i}/#inbox`,
307          // https://mail.google.com/mail/u/${i}/h/1skwmxqy8dsdn/?&
308          {
309            waitUntil: "domcontentloaded",
310            timeout: 1000 * 60 * 5,
311          }
312        );
313        await page.bringToFront();
314        for (let i = 0; i < 20; i++) {
315          await sleep(5000);
316          await page.waitForSelector('[aria-label="Search mail"]');
317
318          await page.bringToFront();
319          await page.click('[aria-label="Search mail"]');
320          await page.bringToFront();
321          if (i == 0) {
322            await page.type(
323              '[aria-label="Search mail"]',
324              `in:inbox welcome OR liberty `
325            );
326          }
327          await page.bringToFront();
328          // is:unread in:inbox welcome OR liberty
329
330          await Promise.all([page.keyboard.press("Enter")]);
331          await page.bringToFront();
332          logger.log("mailsync:", i);
333          // document.getElementsByClassName('v1')[0].innerText == 'Loading...'
334          if (i == 0) {
335            await sleep(15000);
336            await page.bringToFront();
337          } else {
338            await sleep(5000);
339          }
340
341          await page.bringToFront();
342          await eval(
343            page,
344            `() => document.getElementsByClassName('xY a4W')[10].click()`
345          );
346          await page.bringToFront();
347          // const firstmail = await page.$x(
348          //   "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[3]/div[5]/div[2]/div/table/tbody/tr[1]"
349          // );
350
351          // if (firstmail[0] == undefined) {
352          //   const firstmailoptional = await page.$x(
353          //     "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[2]/div[5]/div[2]/div/table/tbody/tr[1]"
354          //   );
355          //   await sleep(2000);
356          //   await firstmailoptional[0].click();
357          // } else {
358          //   await firstmail[0].click();
359          // }
360
361          await page.bringToFront();
362          let pages13 = await browser.pages();
363          if (pages13[1]) {
364            await pages13[1].close();
365          }
366          await page.bringToFront();
367
368          await sleep(3000);
369          let pages14 = await browser.pages();
370          if (pages14[1]) {
371            await pages14[1].close();
372          }
373          await page.bringToFront();
374          const aElementsWithHi = await page.$x("//a[contains(string(),'Hi ')]");
375          if (aElementsWithHi.length) {                
376            if (aElementsWithHi[0] >= 1) {
377              aElementsWithHi[0].click();
378            } else {
379              await sleep(2000)
380              await page.bringToFront();
381              const headerWithHi = await page.$x("//a[contains(string(),'Hi')]");
382              headerWithHi[0].click();
383            }
384            await page.bringToFront();
385            await sleep(7000);
386            await page.bringToFront();
387
388            let pages2 = await browser.pages();
389            if (pages2[1]) {
390              await pages2[1].close();
391            }
392            if (pages2[2]) {
393              await pages2[2].close();
394            }
395            if (pages2[3]) {
396              await pages2[3].close();
397            }
398
399            await page.bringToFront();
400            const starclick = await page.$x(
401              "//div[contains(@aria-label, 'Not starred')]"
402            );
403            await sleep(2000);
404            await page.bringToFront();
405            if (starclick.length >= 1) {
406              await starclick[0].click();
407            }
408            await sleep(8000);
409            await page.bringToFront();
410            let impcheck = await eval(
411              page,
412              `() => document.getElementsByClassName('pG')[20].ariaLabel`
413            );
414            await sleep(1000);
415            // console.log(impcheck)
416            await page.bringToFront();
417
418            if (impcheck == "Not important") {
419              const tryagain = await page.$x(
420                "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[4]/div/table/tr/td[1]/div[2]/div[1]/div[2]/div[1]/span/div[1]"
421              );
422              
423              
424              if(tryagain[0] == undefined){
425                const tryagain1 = await page.$x(
426                  "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[3]/div/table/tr/td[1]/div[2]/div[1]/div[2]/div[1]/span/div[1]"
427                );
428                await tryagain1[0].click();
429              }else{
430              await tryagain[0].click();
431              }
432            }
433            await page.bringToFront();
434
435            // const  impclick = await page.$x(
436            //   "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[4]/div/table/tr/td[1]/div[2]/div[1]/div[2]/div[1]/span"
437            // );
438            // // await sleep(1000);
439
440            // if (impclick.length >= 1) {
441            //   await impclick[0].click();
442            // }
443
444            // await sleep(2000)
445            // document.getElementsByClassName('bAq')[0].innerText == 'Conversation marked as not important.'
446
447            // try{
448
449            //         let impcheck = await eval(
450            //           page,
451            //           `() => document.getElementsByClassName('bAq')`
452            //         );
453            //         console.log(impcheck)
454            //         if (impcheck == true) {
455            //           const  confirmimpclick = await page.$x(
456            //             "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[4]/div/table/tr/td[1]/div[2]/div[1]/div[2]/div[1]/span"
457            //           );
458
459            //           if (confirmimpclick.length >= 1) {
460            //             await confirmimpclick[0].click();
461            //           }
462
463            //         }
464            //       }catch(ex)
465            // {
466            //   console.log(ex)
467            // }
468
469            await page.bringToFront();
470          }
471          await sleep(3000);
472          await page.bringToFront();
473          const Archive = await page.$x(
474            "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[1]/div[4]/div[1]/div/div[2]/div[1]"
475          );
476
477          if (Archive[0]) {
478            await Archive[0].click();
479          } else {
480            const Archive1 = await page.$x(
481              "/html/body/div[7]/div[3]/div/div[2]/div[1]/div[2]/div/div/div/div/div[1]/div[3]/div[1]/div/div[2]/div[1]"
482            );
483            await Archive1[0].click();
484          }
485          await page.bringToFront();
486          await Promise.all([page.keyboard.press("Enter")]);
487        await Promise.all([page.keyboard.press("Enter")]);
488        }
489      }
490    }
491
492    //   await browser.close();
493    // processBrowsers(browser,page)
494    return "DONE";
495  } catch (ex) {
496    console.log(ex);
497  }
498}
499
500module.exports = {
501  gmailProcess,
502};
503
504const sleep = (time) => {
505  return new Promise((resolve) => {
506    setTimeout(() => {
507      resolve(true);
508    }, time);
509  });
510};
511const pressenter = async (page,i) =>{
512  if(i == 0){
513    await sleep(1000)
514  }
515  else{
516  await Promise.all([page.keyboard.press("Enter")]);
517  await Promise.all([page.keyboard.press("Enter")]);
518  }
519}
520
521const eval = async (page, pageFunction, ...args) => {
522  var context = await page._frameManager.mainFrame().executionContext(),
523    suffix = `//# sourceURL=VM30`;
524  var res = await context._client.send("Runtime.callFunctionOn", {
525    functionDeclaration: pageFunction.toString() + "\n" + suffix + "\n",
526    executionContextId: context._contextId,
527    arguments: args.map((arg) => ({ value: arg })),
528    returnByValue: true,
529    awaitPromise: true, 
530    userGesture: true,
531  });
532  if (res.exceptionDetails)
533    throw new Error(res.exceptionDetails.exception.description);
534  else if (res.result.value) return res.result.value;
535};
536
Full Screen

loginonly.js

Source: loginonly.js Github

copy
1const puppeteer = require("puppeteer-extra");
2const EventEmitter = require("events");
3const StealthPlugin = require("puppeteer-extra-plugin-stealth");
4// const utils = require('./utils.js');
5var fs = require('fs')
6
7var logger = require('tracer').console({
8  transport: function(data) {
9    console.log(data.output)
10    fs.appendFile('./loginStatus.log', data.rawoutput + '\n', err => {
11      if (err) throw err
12    })
13  }
14})
15// const proxy_check = require('proxy-check');
16
17require("puppeteer-extra-plugin-stealth/evasions/defaultArgs");
18require("puppeteer-extra-plugin-stealth/evasions/chrome.app");
19require("puppeteer-extra-plugin-stealth/evasions/chrome.csi");
20require("puppeteer-extra-plugin-stealth/evasions/chrome.loadTimes");
21require("puppeteer-extra-plugin-stealth/evasions/chrome.runtime");
22require("puppeteer-extra-plugin-stealth/evasions/iframe.contentWindow");
23require("puppeteer-extra-plugin-stealth/evasions/media.codecs");
24require("puppeteer-extra-plugin-stealth/evasions/navigator.hardwareConcurrency");
25require("puppeteer-extra-plugin-stealth/evasions/navigator.languages");
26require("puppeteer-extra-plugin-stealth/evasions/navigator.permissions");
27require("puppeteer-extra-plugin-stealth/evasions/navigator.plugins");
28require("puppeteer-extra-plugin-stealth/evasions/navigator.vendor");
29require("puppeteer-extra-plugin-stealth/evasions/navigator.webdriver");
30require("puppeteer-extra-plugin-stealth/evasions/sourceurl");
31require("puppeteer-extra-plugin-stealth/evasions/user-agent-override");
32require("puppeteer-extra-plugin-stealth/evasions/webgl.vendor");
33require("puppeteer-extra-plugin-stealth/evasions/window.outerdimensions");
34require("dotenv").config();
35puppeteer.use(StealthPlugin());
36const emitter = new EventEmitter();
37
38emitter.setMaxListeners(1000);
39 
40var categorizeSeed = {};
41
42const gmailProcess = async(emailJson) => {
43 
44  for (let i = 0; i < emailJson.length; i++) {
45    // `email_of_${i.seedNo}_${i.browserNo}`
46    if (!categorizeSeed[emailJson[i].seedNo]) {
47      categorizeSeed[emailJson[i].seedNo] = [];
48    }
49    categorizeSeed[emailJson[i].seedNo].push(emailJson[i]);
50  }
51  // console.log("categorizeSeed >>>>>>>>>>", categorizeSeed);
52  if (!Object.keys(categorizeSeed).length) return;
53
54  let seedLen = Object.keys(categorizeSeed).length;
55  for (let index = 1; index <= seedLen; index++) {
56    if (categorizeSeed[index]) {
57       params = { seedNo: "above seed", browserNumber: index + 1 }
58    //   await utils.checkCpuAndDelay(params);
59      processBrowsers(categorizeSeed[index], index);
60    }
61  }
62
63};
64 
65const processBrowsers = async (browsersArr, browserNo) => {
66 
67  
68  for (let index = 0; index <= browsersArr.length; index++) {
69    // const params = { seedNo: index + 1, browserNumber: browserNo }
70    // await utils.checkCpuAndDelay(params);
71    if(browsersArr.length == index){
72      index = 0
73    }
74    const item = browsersArr[index];
75    const browserArr = browsersArr
76    // try{
77    //   const proxy = `${item.proxyUsername}:${item.proxyPassword}@${item.proxyIP}:${item.proxyPort}`; 
78    //   proxy_check(proxy)
79    const sessionData = `${browserNo}`;
80   
81      const args = [
82      // `--proxy-server=http://${item.proxyIP.trim()}:${item.proxyPort.trim()}`,
83      '--no-sandbox',
84      '--disable-setuid-sandbox',
85      '--disable-infobars',
86      '--window-position=0,0',
87      '--ignore-certifcate-errors',
88      '--ignore-certifcate-errors-spki-list',
89      '--use-gl=egl',
90      '--disable-background-timer-throttling',
91      '--enable-automation',
92      '--disable-renderer-backgrounding',
93      '--disable-backgrounding-occluded-windows',
94      '--disable-ipc-flooding-protection',
95    ];
96  
97    
98
99    const lauchoptions = {
100      executablePath:
101        "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
102      args,
103      userDataDir: sessionData,
104      headless: false,
105      devtools: false,
106      ignoreHTTPSErrors: true,
107    };
108    // let browser = null;
109    // let page = null;
110  // if (item.browserNo == 1) {
111  const browser = await puppeteer.launch(lauchoptions);
112  const page = (await browser.pages())[0];
113  //  var page = (await browser.pages())[0];
114  // }
115
116//   await utils.checkCpuAndDelay(params);
117    await Mainflow(
118      browser,
119      {
120        proxyUsername: item.proxyUsername,
121        proxyPassword: item.proxyPassword,
122        recovery: item.recovery,
123        email: item.email,
124        pwd: item.pwd,
125        seedno: item.seedNo,
126        browserNumber: item.browserNo
127      },
128      page,
129      browserArr
130    );
131  
132  }
133};
134
135async function Mainflow(browser, currentItem, page, browserArr) {
136
137  try {
138    await page.setDefaultNavigationTimeout(1000 * 60 * 3);
139  }
140  catch(ex) {
141    console.error(ex)
142   await browser.close()
143  }
144  await page.bringToFront();
145  await sleep(5000);
146  // await page.authenticate({
147  //   username: currentItem.proxyUsername,
148  //   password: currentItem.proxyPassword,
149  // });
150  await page.bringToFront();
151  await sleep(3000);
152  if ((await page.$('#reload-button')) !== null) {
153    await page.click('#reload-button');
154  }
155  if(currentItem.seedno == 1) {
156    // try{
157  await page.goto("http://accounts.google.com ", {
158    waitUntil: "domcontentloaded",
159    timeout: 0,
160  });
161// } catch(ex){
162//   await browser.close()
163// } 
164  }
165
166  await sleep(3000);
167  if ((await page.$('#reload-button')) !== null) {
168    await page.click('#reload-button');
169  }
170  // let pages1 = await browser.pages();
171  // await pages1[0].close();
172  if ((await page.$('div[class="BHzsHc"]')) !== null) {
173    await page.click('div[class="BHzsHc"]');
174  }
175  if ((await page.$('input[type="email"]')) !== null) {
176    await sleep(3000);
177    // await page.waitForSelector('input[type="email"]');
178    // await page.type('input[type="email"]', currentItem.email);
179    const email = await page.$x("//input[@type='email'] ");
180    await sleep(5000);
181
182    await email[0].type(currentItem.email);
183    await page.bringToFront();
184    await Promise.all([page.keyboard.press("Enter")]);
185    await sleep(5000);
186    // await page.waitForSelector('input[type="password"]');
187    await page.bringToFront();
188    // await sleep(3000);
189    // await page.type('input[type="password"]', currentItem.pwd),
190    const pwd = await page.$x("//input[@type='password'] ");
191    await sleep(5000);
192
193    await pwd[0].type(currentItem.pwd);
194      await sleep(6000);
195    await Promise.all([page.keyboard.press("Enter")]);
196  }
197  await sleep(3000);
198  if ((await page.$('#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span')) !== null) {
199    await page.click('#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span');
200  }
201  await sleep(3000);
202  // if ((await page.$('div[class="lCoei YZVTmd SmR8"]')) !== null) {
203  //   await page.waitForSelector('div[class="lCoei YZVTmd SmR8"]');
204  //   await sleep(3000);
205  //   await page.click('div[class="lCoei YZVTmd SmR8"]');
206  //   // await page.click('div[class="vxx8jf"]');
207  //   await sleep(3000);
208  //   await page.waitForSelector('input[type="email"]');
209  //   await sleep(3000);
210  //   await page.type('input[type="email"]', currentItem.recovery);
211  //   await page.bringToFront();
212  //   await Promise.all([page.keyboard.press("Enter")]);
213  // }
214  if ((await page.$('div[class="lCoei YZVTmd SmR8"]')) !== null) {
215    const doesntHave = await page.$x("//*[@class='vxx8jf']");
216    if (doesntHave[2]) {
217      await doesntHave[2].click();
218      await sleep(3000);
219      await page.waitForSelector('input[type="email"]');
220      await sleep(3000);
221      await page.type('input[type="email"]', currentItem.recovery);
222      await page.bringToFront();
223      await Promise.all([page.keyboard.press("Enter")]);
224      // await sleep(6000)
225    } else {
226      await page.waitForSelector('div[class="lCoei YZVTmd SmR8"]');
227      await sleep(3000);
228      await page.click('div[class="lCoei YZVTmd SmR8"]');
229      // await page.click('div[class="vxx8jf"]');
230      await sleep(3000);
231      await page.waitForSelector('input[type="email"]');
232      await sleep(3000);
233      await page.type('input[type="email"]', currentItem.recovery);
234      await page.bringToFront();
235      await Promise.all([page.keyboard.press("Enter")]);
236    }
237  }
238  //not now click
239  await sleep(3000);
240  if ((await page.$('div[class="VfPpkd-RLmnJb"]')) !== null) {
241    await sleep(3000);
242    await page.click('div[class="VfPpkd-RLmnJb"]');
243  }
244  if (
245    (await page.$(
246      "#yDmH0d > c-wiz > div > div > div > div.L5MEH.Bokche.ypEC4c > div.lq3Znf > div:nth-child(1) > button > div.VfPpkd-RLmnJb"
247    )) !== null
248  ) {
249    await sleep(3000);
250    await page.click(
251      "#yDmH0d > c-wiz > div > div > div > div.L5MEH.Bokche.ypEC4c > div.lq3Znf > div:nth-child(1) > button > div.VfPpkd-RLmnJb"
252    );
253  }
254  if (
255    (await page.$(
256      "#yDmH0d > c-wiz > div > div > div > div.L5MEH.Bokche.ypEC4c > div.lq3Znf > div:nth-child(1) > button > span"
257    )) !== null
258  ) {
259    await sleep(3000);
260    await page.click(
261      "#yDmH0d > c-wiz > div > div > div > div.L5MEH.Bokche.ypEC4c > div.lq3Znf > div:nth-child(1) > button > span"
262    );
263  }
264
265  await page.bringToFront();
266  //confirm click
267  if (
268    (await page.$(
269      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span"
270    )) !== null
271  ) {
272    await sleep(3000);
273    await page.click(
274      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span"
275    );
276    await page.bringToFront();
277  }
278  if (
279    (await page.$(
280      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > div.ZFr60d.CeoRYc"
281    )) !== null
282  ) {
283    await sleep(3000);
284    await page.click(
285      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > div.ZFr60d.CeoRYc"
286    );
287  }
288
289  if ((await page.$('div[class="ZFr60d"]')) !== null) {
290    await sleep(3000);
291    await page.click('div[class="ZFr60d"]');
292  }
293  if (
294    (await page.$(
295      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span"
296    )) !== null
297  ) {
298    await sleep(3000);
299    await page.click(
300      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span"
301    );
302  }
303  if ((await page.$('div[class="VfPpkd"]')) !== null) {
304    await sleep(3000);
305    await page.click('div[class="VfPpkd"]');
306
307  }
308  logger.log(`email:${currentItem.email} login sucessfully`)
309  
310  
311  // 1
312  for (let i = 1; i <= 10; i++) {
313    try{
314    if (i == 10) {
315      logger.log('all user login sucessfully');
316      break;
317    }
318  await sleep(5000);
319  await page.bringToFront();
320  // await page.authenticate({
321  //   username: browserArr[1].proxyUsername,
322  //   password: browserArr[1].proxyPassword,
323  // });
324  let pages5 = await browser.pages();
325  if(pages5[1]){
326  await pages5[1].close();
327  }
328  await sleep(3000);
329  if ((await page.$('#reload-button')) !== null) {
330    await page.click('#reload-button');
331  }
332  await page.bringToFront();
333  try{
334  await page.goto("https://accounts.google.com/signin/v2/identifier?service=accountsettings&continue=https%3A%2F%2Fmyaccount.google.com%2F%3Fpli%3D1&ec=GAlAwAE&flowName=GlifWebSignIn&flowEntry=AddSession", {
335    waitUntil: "domcontentloaded",
336    timeout: 0,
337  });
338} catch(ex){
339  await browser.close()
340} 
341await page.bringToFront();
342  
343  
344
345  await sleep(3000);
346  if ((await page.$('#reload-button')) !== null) {
347    await page.click('#reload-button');
348  }
349  await page.bringToFront();
350  // let pages11 = await browser.pages();
351  // await pages11[0].close();
352  if ((await page.$('div[class="BHzsHc"]')) !== null) {
353    await page.click('div[class="BHzsHc"]');
354  }
355  await page.bringToFront();
356  await page.bringToFront();
357  if ((await page.$('input[type="email"]')) !== null) {
358    await sleep(3000);
359    await page.waitForSelector('input[type="email"]');
360    await page.type('input[type="email"]', browserArr[i].email);
361    await Promise.all([page.keyboard.press("Enter")]);
362    await sleep(5000);
363    await page.waitForSelector('input[type="password"]');
364    await sleep(3000);
365    await page.type('input[type="password"]', browserArr[i].pwd),
366      await sleep(6000);
367    await Promise.all([page.keyboard.press("Enter")]);
368  }
369  
370  await page.bringToFront();
371  await sleep(3000);
372  if ((await page.$('#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span')) !== null) {
373    await page.click('#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span');
374  }
375  await sleep(3000);
376  await page.bringToFront();
377  if ((await page.$('div[class="lCoei YZVTmd SmR8"]')) !== null) {
378    await page.waitForSelector('div[class="lCoei YZVTmd SmR8"]');
379    await sleep(3000);
380    await page.click('div[class="lCoei YZVTmd SmR8"]');
381    // await page.click('div[class="vxx8jf"]');
382    await sleep(3000);
383    await page.bringToFront();
384    await page.waitForSelector('input[type="email"]');
385    await sleep(3000);
386    await page.type('input[type="email"]', browserArr[i].recovery);
387    await Promise.all([page.keyboard.press("Enter")]);
388  }
389  await page.bringToFront();
390  //not now click
391  await page.bringToFront();
392  await sleep(3000);
393  if ((await page.$('div[class="VfPpkd-RLmnJb"]')) !== null) {
394    await sleep(3000);
395    await page.click('div[class="VfPpkd-RLmnJb"]');
396  }
397  await page.bringToFront();
398  if (
399    (await page.$(
400      "#yDmH0d > c-wiz > div > div > div > div.L5MEH.Bokche.ypEC4c > div.lq3Znf > div:nth-child(1) > button > div.VfPpkd-RLmnJb"
401    )) !== null
402  ) {
403    await sleep(3000);
404    await page.click(
405      "#yDmH0d > c-wiz > div > div > div > div.L5MEH.Bokche.ypEC4c > div.lq3Znf > div:nth-child(1) > button > div.VfPpkd-RLmnJb"
406    );
407  }
408  await page.bringToFront();
409  if (
410    (await page.$(
411      "#yDmH0d > c-wiz > div > div > div > div.L5MEH.Bokche.ypEC4c > div.lq3Znf > div:nth-child(1) > button > span"
412    )) !== null
413  ) {
414    await sleep(3000);
415    await page.click(
416      "#yDmH0d > c-wiz > div > div > div > div.L5MEH.Bokche.ypEC4c > div.lq3Znf > div:nth-child(1) > button > span"
417    );
418  }
419  await page.bringToFront();
420
421  //confirm click
422  if (
423    (await page.$(
424      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span"
425    )) !== null
426  ) {
427    await sleep(3000);
428    await page.click(
429      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span"
430    );
431  }
432  await page.bringToFront();
433  if (
434    (await page.$(
435      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > div.ZFr60d.CeoRYc"
436    )) !== null
437  ) {
438    await sleep(3000);
439    await page.click(
440      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > div.ZFr60d.CeoRYc"
441    );
442  }
443  await page.bringToFront();
444
445  if ((await page.$('div[class="ZFr60d"]')) !== null) {
446    await sleep(3000);
447    await page.click('div[class="ZFr60d"]');
448  }
449  await page.bringToFront();
450  if (
451    (await page.$(
452      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span"
453    )) !== null
454  ) {
455    await sleep(3000);
456    await page.click(
457      "#yDmH0d > c-wiz.yip5uc.SSPGKf > c-wiz > div > div.p9lFnc > div > div > div > div.ZRg0lb.Kn8Efe > div:nth-child(3) > div > div.yKBrKe > div > span > span"
458    );
459  }
460  await page.bringToFront();
461  if ((await page.$('div[class="VfPpkd"]')) !== null) {
462    await sleep(3000);
463    await page.click('div[class="VfPpkd"]');
464  }
465  await page.bringToFront();
466  logger.log(`email:${browserArr[i].email} login sucessfully`)
467}catch(err){
468  logger.log(`email:${browserArr[i].email} NOT LOGIN`)
469  continue;
470}
471}
472
473
474
475await page.bringToFront();
476  
477
478    //  await browser.close();
479
480 
481     return "DONE";
482}
483
484
485
486
487module.exports = {
488  gmailProcess,
489};
490
491const sleep = (time) => {
492  return new Promise((resolve) => {
493    setTimeout(() => {
494      resolve(true);
495    }, time);
496  });
497};
498
Full Screen

TrackerManager.js

Source: TrackerManager.js Github

copy
1///<reference path="DEDesigner.ts"/>
2///<reference path="../Util.ts"/>
3var DEJS;
4(function (DEJS) {
5    var TrackerManager = (function () {
6        function TrackerManager(designer) {
7            this.trackers = {};
8            this.zoom = 100;
9            this.lockProportions = true;
10            this.designer = designer;
11        }
12        TrackerManager.prototype.track = function (element, forceRedraw) {
13            var _this = this;
14            if (typeof forceRedraw === "undefined") { forceRedraw = false; }
15            if (element) {
16                var tracker = this.trackers[element.id];
17                if (!tracker)
18                    tracker = this.trackers[element.id] = new Tracker(element, this.designer.canvas, function (action) {
19                        return _this.onTrackerMouseDown(action);
20                    }, this);
21                else
22                    tracker.update(forceRedraw);
23            } else {
24                for (var key in this.trackers) {
25                    this.trackers[key].update(forceRedraw);
26                }
27            }
28        };
29
30        TrackerManager.prototype.stopTrack = function (element) {
31            if (element) {
32                var tracker = this.trackers[element.id];
33                if (tracker) {
34                    tracker.remove();
35                    delete this.trackers[element.id];
36                }
37            } else {
38                this.clear();
39            }
40        };
41
42        TrackerManager.prototype.clear = function () {
43            for (var key in this.trackers) {
44                this.trackers[key].remove();
45                delete this.trackers[key];
46            }
47        };
48
49        TrackerManager.prototype.processClick = function (x, y) {
50            for (var key in this.trackers) {
51                var tracker = this.trackers[key];
52                if (tracker.processClick(x, y))
53                    return true;
54            }
55            return false;
56        };
57
58        TrackerManager.prototype.setLockProportions = function (lockProportions) {
59            if (lockProportions == this.lockProportions)
60                return;
61            this.lockProportions = lockProportions;
62            this.track(null, true);
63        };
64
65        TrackerManager.prototype.onTrackerMouseDown = function (action) {
66            this.designer.trackerAction(action);
67        };
68
69        TrackerManager.prototype.markTracker = function (element) {
70            element.node.isTracker = true;
71            return element;
72        };
73
74        TrackerManager.prototype.setZoom = function (zoom) {
75            if (zoom == this.zoom)
76                return;
77            this.zoom = zoom;
78            this.track();
79        };
80        return TrackerManager;
81    })();
82    DEJS.TrackerManager = TrackerManager;
83
84    var Tracker = (function () {
85        function Tracker(element, canvas, mouseHandler, trackerManager) {
86            this.element = element;
87            this.canvas = canvas;
88            this.mouseHandler = mouseHandler;
89            this.trackerManager = trackerManager;
90            this.draw();
91        }
92        Tracker.prototype.draw = function () {
93            var obj = this.element.node.objectLink;
94            var bbox = DEJS.Util.getBBox(this.element, true);
95            this.lastBBox = bbox;
96
97            var boxColor = "#494949";
98            var padding = 0;
99            var x, y;
100
101            this.box = this.canvas.rect(bbox.x - padding, bbox.y - padding, bbox.width + padding * 2, bbox.height + padding * 2).attr({ "opacity": 0.7, "stroke": boxColor, "stroke-dasharray": "- " });
102            var preloaderSize = Math.min(bbox.width + padding * 2, bbox.height + padding * 2);
103            this.preloader = this.canvas.image(DEJS.Model.ConfigManager.imagePreloaderPath(), bbox.x + ((bbox.width + padding * 2) - preloaderSize) / 2, bbox.y + ((bbox.height + padding * 2) - preloaderSize) / 2, preloaderSize, preloaderSize); //.attr({ "opacity": 0.7 });
104            this.preloader.hide();
105            if (obj && obj.canRotate()) {
106                x = this.getTrackerXY(DEJS.Action.Rotate, bbox).x;
107                y = this.getTrackerXY(DEJS.Action.Rotate, bbox).y;
108                this.rotateEl = this.trackerIcon(x, y, DEJS.Action.Rotate);
109            }
110            if (obj && obj.canDelete()) {
111                x = this.getTrackerXY(DEJS.Action.Delete, bbox).x;
112                y = this.getTrackerXY(DEJS.Action.Delete, bbox).y;
113                this.deleteEl = this.trackerIcon(x, y, DEJS.Action.Delete);
114            }
115            if (obj && obj.canResize()) {
116                if (!this.trackerManager.lockProportions) {
117                    x = this.getTrackerXY(DEJS.Action.ResizeH, bbox).x;
118                    y = this.getTrackerXY(DEJS.Action.ResizeH, bbox).y;
119                    this.resizeHEl = this.trackerIcon(x, y, DEJS.Action.ResizeH);
120                    x = this.getTrackerXY(DEJS.Action.ResizeV, bbox).x;
121                    y = this.getTrackerXY(DEJS.Action.ResizeV, bbox).y;
122                    this.resizeVEl = this.trackerIcon(x, y, DEJS.Action.ResizeV);
123                }
124                x = this.getTrackerXY(DEJS.Action.Resize, bbox).x;
125                y = this.getTrackerXY(DEJS.Action.Resize, bbox).y;
126                this.resizeEl = this.trackerIcon(x, y, DEJS.Action.Resize);
127            }
128            //-----
129            x = this.getTrackerXY(DEJS.Action.BringToFront, bbox).x;
130            y = this.getTrackerXY(DEJS.Action.BringToFront, bbox).y;
131            this.BringToFront = this.trackerIcon(x, y, DEJS.Action.BringToFront);
132            //-----
133
134            this.update();
135        };
136
137        Tracker.prototype.update = function (forceRedraw) {
138            if (typeof forceRedraw === "undefined") { forceRedraw = false; }
139            var bbox = DEJS.Util.getBBox(this.element, true);
140            if (forceRedraw || (bbox.width != this.lastBBox.width || bbox.height != this.lastBBox.height)) {
141                this.remove();
142                this.draw();
143                return;
144            }
145            var padding = 0;
146            var transform = this.element.transform();
147            var matrix = this.element.matrix;
148
149            //var r = this.element.matrix.split().rotate;
150            var r = DEJS.Util.getMatrixRotate(matrix, bbox.x + bbox.width / 2, bbox.y + bbox.height / 2);
151            var scaleX = DEJS.Util.getMatrixScaleX(matrix);
152            var scaleY = DEJS.Util.getMatrixScaleY(matrix);
153            var x;
154            var y;
155            var x2;
156            var y2;
157            if (this.box) {
158                x = this.getTrackerXY("", bbox).x;
159                y = this.getTrackerXY("", bbox).y;
160                x2 = matrix.x(x, y);
161                y2 = matrix.y(x, y);
162
163                var newWidth = bbox.width * Math.abs(scaleX) * this.trackerManager.zoom / 100;
164                var newHeight = bbox.height * Math.abs(scaleY) * this.trackerManager.zoom / 100;
165                this.box.attr({ x: x2, y: y2, width: newWidth, height: newHeight });
166                var ns = 100 / this.trackerManager.zoom;
167                this.box.transform("s" + ns + "," + ns + "," + x2 + "," + y2 + "r" + r + "," + x2 + "," + y2);
168                if (this.preloader) {
169                    var preloaderSize = Math.min(newWidth, newHeight);
170                    this.preloader.attr({ x: x2 + (newWidth - preloaderSize) / 2, y: y2 + (newHeight - preloaderSize) / 2, width: preloaderSize, height: preloaderSize });
171                    this.preloader.transform("s" + ns + "," + ns + "," + x2 + "," + y2 + "r" + r + "," + x2 + "," + y2);
172                    var obj = this.element.node.objectLink;
173                    if (obj && obj.showPreloader) {
174                        this.preloader.show();
175                    } else {
176                        this.preloader.hide();
177                    }
178                }
179            }
180            if (this.resizeEl) {
181                x = this.getTrackerXY(DEJS.Action.Resize, bbox).x;
182                y = this.getTrackerXY(DEJS.Action.Resize, bbox).y;
183                x2 = matrix.x(x, y);
184                y2 = matrix.y(x, y);
185                this.resizeEl.transform("t" + (x2 - x) + "," + (y2 - y) + "r" + r);
186                DEJS.Util.scaleElement(this.resizeEl, 100 / this.trackerManager.zoom, true);
187            }
188            if (this.resizeHEl) {
189                x = this.getTrackerXY(DEJS.Action.ResizeH, bbox).x;
190                y = this.getTrackerXY(DEJS.Action.ResizeH, bbox).y;
191                x2 = matrix.x(x, y);
192                y2 = matrix.y(x, y);
193                this.resizeHEl.transform("t" + (x2 - x) + "," + (y2 - y) + "r" + r);
194                DEJS.Util.scaleElement(this.resizeHEl, 100 / this.trackerManager.zoom, true);
195            }
196            if (this.resizeVEl) {
197                x = this.getTrackerXY(DEJS.Action.ResizeV, bbox).x;
198                y = this.getTrackerXY(DEJS.Action.ResizeV, bbox).y;
199                x2 = matrix.x(x, y);
200                y2 = matrix.y(x, y);
201                this.resizeVEl.transform("t" + (x2 - x) + "," + (y2 - y) + "r" + r);
202                DEJS.Util.scaleElement(this.resizeVEl, 100 / this.trackerManager.zoom, true);
203            }
204            if (this.rotateEl) {
205                x = this.getTrackerXY(DEJS.Action.Rotate, bbox).x;
206                y = this.getTrackerXY(DEJS.Action.Rotate, bbox).y;
207                x2 = matrix.x(x, y);
208                y2 = matrix.y(x, y);
209                this.rotateEl.transform("t" + (x2 - x) + "," + (y2 - y) + "r" + r);
210                DEJS.Util.scaleElement(this.rotateEl, 100 / this.trackerManager.zoom, true);
211            }
212            if (this.deleteEl) {
213                x = this.getTrackerXY(DEJS.Action.Delete, bbox).x;
214                y = this.getTrackerXY(DEJS.Action.Delete, bbox).y;
215                x2 = matrix.x(x, y);
216                y2 = matrix.y(x, y);
217                this.deleteEl.transform("t" + (x2 - x) + "," + (y2 - y) + "r" + r);
218                DEJS.Util.scaleElement(this.deleteEl, 100 / this.trackerManager.zoom, true);
219            }
220            if (this.moveEl) {
221                x = this.getTrackerXY(DEJS.Action.Move, bbox).x;
222                y = this.getTrackerXY(DEJS.Action.Move, bbox).y;
223                x2 = matrix.x(x, y);
224                y2 = matrix.y(x, y);
225                this.moveEl.transform("t" + (x2 - x) + "," + (y2 - y) + "r" + r);
226                DEJS.Util.scaleElement(this.moveEl, 100 / this.trackerManager.zoom, true);
227            }
228            //-----
229            if (this.BringToFront) {
230                x = this.getTrackerXY(DEJS.Action.BringToFront, bbox).x;
231                y = this.getTrackerXY(DEJS.Action.BringToFront, bbox).y;
232                x2 = matrix.x(x, y);
233                y2 = matrix.y(x, y);
234                this.BringToFront.transform("t" + (x2 - x) + "," + (y2 - y) + "r" + r);
235                DEJS.Util.scaleElement(this.BringToFront, 100 / this.trackerManager.zoom, true);
236            }
237            //-----
238        };
239
240        Tracker.prototype.remove = function () {
241            this.box.remove();
242            if (this.preloader)
243                this.preloader.remove();
244            if (this.resizeEl)
245                this.resizeEl.remove();
246            if (this.resizeHEl)
247                this.resizeHEl.remove();
248            if (this.resizeVEl)
249                this.resizeVEl.remove();
250            if (this.rotateEl)
251                this.rotateEl.remove();
252            if (this.deleteEl)
253                this.deleteEl.remove();
254            if (this.moveEl)
255                this.moveEl.remove();
256            //-----
257            if (this.BringToFront)
258                this.BringToFront.remove();
259            //-----
260        };
261
262        Tracker.prototype.trackerIcon = function (x, y, action) {
263            var _this = this;
264
265            var w = mobilesafari ? 32 : 21;
266            var addName = mobilesafari ? "_32px" : "";
267            var element;
268            switch (action) {
269                case DEJS.Action.Resize:
270                    element = this.canvas.image(DEJS.Model.ConfigManager.assetsUrl + "img/tracker/resize" + addName + ".png", x - w / 2, y - w / 2, w, w);
271                    break;
272                case DEJS.Action.ResizeH:
273                    element = this.canvas.image(DEJS.Model.ConfigManager.assetsUrl + "img/tracker/resizeH" + addName + ".png", x - w / 2, y - w / 2, w, w);
274                    break;
275                case DEJS.Action.ResizeV:
276                    element = this.canvas.image(DEJS.Model.ConfigManager.assetsUrl + "img/tracker/resizeV" + addName + ".png", x - w / 2, y - w / 2, w, w);
277                    break;
278                case DEJS.Action.Rotate:
279                    element = this.canvas.image(DEJS.Model.ConfigManager.assetsUrl + "img/tracker/rotate" + addName + ".png", x - w / 2, y - w / 2, w, w);
280                    break;
281                case DEJS.Action.Delete:
282                    element = this.canvas.image(DEJS.Model.ConfigManager.assetsUrl + "img/tracker/delete" + addName + ".png", x - w / 2, y - w / 2, w, w);
283                    break;
284                //-----
285                case DEJS.Action.BringToFront:
286                    element = this.canvas.image(DEJS.Model.ConfigManager.assetsUrl + "img/tracker/bringtofront" + addName + ".png", x - w / 2, y - w / 2, w, w);
287                    break;
288                //-----
289                default:
290                    element = this.canvas.ellipse(x, y, w / 2, w / 2).attr({
291                        "stroke-width": 1,
292                        "stroke": "grey",
293                        "fill": "white"
294                    });
295                    break;
296            }
297            element.node.id = "de-tracker-" + action;
298            element.attr("cursor", "pointer").mouseover(function () {
299                this.attr("fill", "grey");
300            }).mouseout(function () {
301                this.attr("fill", "white");
302            }).mousedown(function (event) {
303                return _this.onTrackerMouseDown(event, action);
304            }).dblclick(function (dblclickEvent) {
305                //this.paper.editor.trackers[0].object.rotate(0, true);
306                //this.paper.editor.updateTracker();
307            });
308            if (mobilesafari) {
309                element.node.addEventListener("touchstart", function (event) {
310                    return _this.onTrackerMouseDown(event, action);
311                }, false);
312            }
313            this.markTracker(element);
314            return element;
315        };
316
317        Tracker.prototype.onTrackerMouseDown = function (event, action) {
318            if (this.mouseHandler)
319                this.mouseHandler(action);
320        };
321
322        Tracker.prototype.markTracker = function (element) {
323            element.node.isTracker = true;
324            return element;
325        };
326
327        Tracker.prototype.processClick = function (x, y) {
328            if (this.resizeEl && DEJS.Util.isClicked(x, y, this.resizeEl)) {
329                this.onTrackerMouseDown(null, DEJS.Action.Resize);
330                return true;
331            }
332            if (this.resizeHEl && DEJS.Util.isClicked(x, y, this.resizeHEl)) {
333                this.onTrackerMouseDown(null, DEJS.Action.ResizeH);
334                return true;
335            }
336            if (this.resizeVEl && DEJS.Util.isClicked(x, y, this.resizeVEl)) {
337                this.onTrackerMouseDown(null, DEJS.Action.ResizeV);
338                return true;
339            }
340            if (this.rotateEl && DEJS.Util.isClicked(x, y, this.rotateEl)) {
341                this.onTrackerMouseDown(null, DEJS.Action.Rotate);
342                return true;
343            }
344            if (this.deleteEl && DEJS.Util.isClicked(x, y, this.deleteEl)) {
345                this.onTrackerMouseDown(null, DEJS.Action.Delete);
346                return true;
347            }
348            if (this.moveEl && DEJS.Util.isClicked(x, y, this.moveEl)) {
349                this.onTrackerMouseDown(null, DEJS.Action.Move);
350                return true;
351            }
352            //-----
353            if (this.BringToFront && DEJS.Util.isClicked(x, y, this.BringToFront)) {
354                this.onTrackerMouseDown(null, DEJS.Action.BringToFront);
355                return true;
356            }
357            //-----
358            return false;
359        };
360
361        Tracker.prototype.getTrackerXY = function (action, bbox) {
362            var x;
363            var y;
364            var padding = 0;
365            switch (action) {
366                case DEJS.Action.Resize:
367                    x = bbox.x + bbox.width + padding;
368                    y = bbox.y + bbox.height + padding;
369                    break;
370                case DEJS.Action.ResizeH:
371                    x = bbox.x + bbox.width + padding;
372                    y = bbox.y + bbox.height / 2;
373                    break;
374                case DEJS.Action.ResizeV:
375                    x = bbox.x + bbox.width / 2;
376                    y = bbox.y + bbox.height + padding;
377                    break;
378                case DEJS.Action.Rotate:
379                    x = bbox.x - padding;
380                    y = bbox.y + bbox.height + padding;
381                    break;
382                case DEJS.Action.Delete:
383                    x = bbox.x + bbox.width + padding;
384                    y = bbox.y - padding;
385                    break;
386                //-----
387                case DEJS.Action.BringToFront:
388                    x = bbox.x - padding;
389                    y = bbox.y - padding;
390                    break;
391                //-----
392                default:
393                    x = bbox.x;
394                    y = bbox.y;
395                    break;
396            }
397            var m = this.element.matrix;
398            var cx = m.x(bbox.x + bbox.width / 2, bbox.y + bbox.height / 2);
399            var cy = m.y(bbox.x + bbox.width / 2, bbox.y + bbox.height / 2);
400            var curRotate = DEJS.Util.getMatrixRotate(m, cx, cy);
401            var m2 = Raphael.matrix(1, 0, 0, 1, 0, 0);
402            m2.rotate(0 - curRotate, cx, cy);
403            m2.add(m.a, m.b, m.c, m.d, m.e, m.f);
404            var flipH = m2.a < 0;
405            var flipV = m2.d < 0;
406            if (flipH)
407                x = 2 * bbox.x + bbox.width - x;
408            if (flipV)
409                y = 2 * bbox.y + bbox.width - y;
410            return { x: x, y: y, flipH: flipH, flipV: flipV };
411        };
412        return Tracker;
413    })();
414    DEJS.Tracker = Tracker;
415})(DEJS || (DEJS = {}));
Full Screen

popup-options.js

Source: popup-options.js Github

copy
1
2var t = require('assert')
3var defaults = require('./utils/defaults')
4
5
6module.exports = ({popup, advanced, content}) => {
7
8  before(async () => {
9    await defaults({popup, advanced, content})
10  })
11
12  describe('button - raw/markdown', () => {
13    before(async () => {
14      // popup
15      await popup.bringToFront()
16      // defaults button
17      await popup.click('button:nth-of-type(2)')
18    })
19
20    it('render markdown as html', async () => {
21      // go to page serving markdown as text/markdown
22      await content.goto('http://localhost:3000/correct-content-type')
23      await content.bringToFront()
24      await content.waitForTimeout(300)
25
26      t.equal(
27        await content.evaluate(() =>
28          document.querySelector('#_html p strong').innerText
29        ),
30        'bold',
31        'markdown should be rendered'
32      )
33
34      // popup
35      await popup.bringToFront()
36
37      t.strictEqual(
38        await popup.evaluate(() =>
39          state.raw
40        ),
41        false,
42        'state.raw should equal false'
43      )
44      t.equal(
45        await popup.evaluate(() =>
46          document.querySelector('.m-button:first-child').innerText.toLowerCase()
47        ),
48        'markdown',
49        'button text should equal markdown'
50      )
51    })
52
53    it('display raw markdown', async () => {
54      // raw button
55      await popup.bringToFront()
56      await popup.click('button:nth-of-type(1)')
57      // content auto reloads, but there is no way to have both tabs active
58      await content.bringToFront()
59      await content.reload()
60
61      t.equal(
62        await content.evaluate(() =>
63          document.querySelector('#_markdown').innerText
64        ),
65        '**bold**',
66        'markdown should not be rendered'
67      )
68
69      // popup
70      await popup.bringToFront()
71
72      t.strictEqual(
73        await popup.evaluate(() =>
74          state.raw
75        ),
76        true,
77        'state.raw should equal true'
78      )
79      t.equal(
80        await popup.evaluate(() =>
81          document.querySelector('.m-button:first-child').innerText.toLowerCase()
82        ),
83        'html',
84        'button text should equal html'
85      )
86    })
87  })
88
89  describe('set theme', () => {
90    before(async () => {
91      // popup
92      await popup.bringToFront()
93      // defaults button
94      await popup.click('button:nth-of-type(2)')
95      // theme tab
96      await popup.click('.m-tabs a:nth-of-type(1)')
97    })
98
99    it('github theme should be set by default', async () => {
100      // go to page serving markdown as text/markdown
101      await content.goto('http://localhost:3000/correct-content-type')
102      await content.bringToFront()
103      await content.waitForTimeout(300)
104
105      t.strictEqual(
106        await content.evaluate(() =>
107          /github\.css$/.test(
108            document.querySelector('#_theme').getAttribute('href')
109          )
110        ),
111        true,
112        'github theme styles should be included'
113      )
114    })
115
116    it('set github-dark theme', async () => {
117      // select github-dark theme
118      await popup.bringToFront()
119      await popup.select('.m-panel:nth-of-type(1) select', 'github-dark')
120      // content auto reloads, but there is no way to have both tabs active
121      await content.bringToFront()
122      await content.reload()
123
124      t.strictEqual(
125        await content.evaluate(() =>
126          /github-dark\.css$/.test(
127            document.querySelector('#_theme').getAttribute('href')
128          )
129        ),
130        true,
131        'github-dark theme styles should be included'
132      )
133    })
134
135    it('popup should preserve state', async () => {
136      // reload popup
137      await popup.bringToFront()
138      await popup.reload()
139      await popup.waitForTimeout(300)
140
141      t.equal(
142        await popup.evaluate(() =>
143          state.theme
144        ),
145        'github-dark',
146        'state.theme should equal github-dark'
147      )
148      t.equal(
149        await popup.evaluate(() =>
150          document.querySelectorAll('.m-panel:nth-of-type(1) select option')[
151            document.querySelector('.m-panel:nth-of-type(1) select').selectedIndex
152          ].innerText
153        ),
154        'github-dark',
155        'dom select option should be github-dark'
156      )
157    })
158  })
159
160  describe('set compiler options - marked', () => {
161    before(async () => {
162      // popup
163      await popup.bringToFront()
164      // defaults button
165      await popup.click('button:nth-of-type(2)')
166      // compiler tab
167      await popup.click('.m-tabs a:nth-of-type(2)')
168    })
169
170    it('gfm is enabled by default', async () => {
171      // go to page serving markdown as text/markdown
172      await content.goto('http://localhost:3000/compiler-options-marked')
173      await content.bringToFront()
174      await content.waitForTimeout(300)
175
176      t.equal(
177        await content.evaluate(() =>
178          document.querySelector('#_html p del').innerText
179        ),
180        'strikethrough',
181        'gfm should be rendered'
182      )
183    })
184
185    it('gfm is disabled', async () => {
186      // disable gfm
187      await popup.bringToFront()
188      // gfm switch
189      await popup.click('.m-panel:nth-of-type(2) .m-switch:nth-of-type(2)')
190      // content auto reloads, but there is no way to have both tabs active
191      await content.bringToFront()
192      await content.reload()
193      await content.waitForTimeout(300)
194
195      t.equal(
196        await content.evaluate(() =>
197          document.querySelector('#_html p').innerText
198        ),
199        '~~strikethrough~~',
200        'gfm should not be rendered'
201      )
202    })
203
204    it('popup should preserve state', async () => {
205      // reload popup
206      await popup.bringToFront()
207      await popup.reload()
208      await popup.waitForTimeout(300)
209
210      t.equal(
211        await popup.evaluate(() =>
212          document.querySelectorAll('.m-panel:nth-of-type(2) .m-select option')[
213            document.querySelector('.m-panel:nth-of-type(2) .m-select').selectedIndex
214          ].innerText
215        ),
216        'marked',
217        'dom select option should be marked'
218      )
219      t.strictEqual(
220        await popup.evaluate(() =>
221          state.options.gfm
222        ),
223        false,
224        'state.options.gfm should be false'
225      )
226      t.strictEqual(
227        await popup.evaluate(() =>
228          document.querySelector('.m-panel:nth-of-type(2) .m-switch:nth-of-type(2)').classList.contains('is-checked')
229        ),
230        false,
231        'dom gfm checkbox should be disabled'
232      )
233    })
234  })
235
236  describe('set compiler options - remark', () => {
237    before(async () => {
238      // popup
239      await popup.bringToFront()
240      // defaults button
241      await popup.click('button:nth-of-type(2)')
242      // compiler tab
243      await popup.click('.m-tabs a:nth-of-type(2)')
244    })
245
246    it('marked should render gfm task lists by default', async () => {
247      // go to page serving markdown as text/markdown
248      await content.goto('http://localhost:3000/compiler-options-remark')
249      await content.bringToFront()
250      await content.waitForTimeout(300)
251
252      t.equal(
253        await content.evaluate(() =>
254          document.querySelector('#_html ul li').getAttribute('class')
255        ),
256        null,
257        'no class on dom li'
258      )
259      t.strictEqual(
260        await content.evaluate(() =>
261          document.querySelector('#_html ul li [type=checkbox]').hasAttribute('disabled')
262        ),
263        true,
264        'dom li should contain checkbox in it'
265      )
266      t.equal(
267        await content.evaluate(() =>
268          document.querySelector('#_html ul li').innerText
269        ),
270        ' task',
271        'dom li should contain the task text'
272      )
273    })
274
275    it('remark should render gfm task lists by default', async () => {
276      // select remark compiler
277      await popup.bringToFront()
278      await popup.select('.m-panel:nth-of-type(2) select', 'remark')
279      // content auto reloads, but there is no way to have both tabs active
280      await content.bringToFront()
281      await content.reload()
282      await content.waitForTimeout(300)
283
284      t.equal(
285        await content.evaluate(() =>
286          document.querySelector('#_html ul li').getAttribute('class')
287        ),
288        'task-list-item',
289        'dom li should have a class set'
290      )
291      t.strictEqual(
292        await content.evaluate(() =>
293          document.querySelector('#_html ul li [type=checkbox]').hasAttribute('disabled')
294        ),
295        true,
296        'dom li should contain checkbox in it'
297      )
298      t.equal(
299        await content.evaluate(() =>
300          document.querySelector('#_html ul li').innerText
301        ),
302        ' task',
303        'dom li should contain the task text'
304      )
305    })
306
307    it('remark disable gfm', async () => {
308      // redraw popup
309      await popup.bringToFront()
310      await popup.reload()
311      await popup.waitForTimeout(300)
312
313      // disable gfm - gfm switch
314      await popup.click('.m-panel:nth-of-type(2) .m-switch[title~=GFM]')
315      // content auto reloads, but there is no way to have both tabs active
316      await content.bringToFront()
317      await content.reload()
318      await content.waitForTimeout(300)
319
320      t.equal(
321        await content.evaluate(() =>
322          document.querySelector('#_html ul li').innerText
323        ),
324        '[ ] task',
325        'gfm task lists should not be rendered'
326      )
327    })
328
329    it('popup should preserve state', async () => {
330      // reload popup
331      await popup.bringToFront()
332      await popup.reload()
333      await popup.waitForTimeout(300)
334
335      t.equal(
336        await popup.evaluate(() =>
337          document.querySelectorAll('.m-panel:nth-of-type(2) .m-select option')[
338            document.querySelector('.m-panel:nth-of-type(2) .m-select').selectedIndex
339          ].innerText
340        ),
341        'remark',
342        'dom select option should be remark'
343      )
344      t.strictEqual(
345        await popup.evaluate(() =>
346          state.options.gfm
347        ),
348        false,
349        'state.options.gfm should be false'
350      )
351      t.strictEqual(
352        await popup.evaluate(() =>
353          document.querySelector('.m-panel:nth-of-type(2) .m-switch[title~=GFM]').classList.contains('is-checked')
354        ),
355        false,
356        'dom gfm checkbox should be disabled'
357      )
358    })
359  })
360
361  describe('set content options - toc', () => {
362    before(async () => {
363      // popup
364      await popup.bringToFront()
365      // defaults button
366      await popup.click('button:nth-of-type(2)')
367      // content tab
368      await popup.click('.m-tabs a:nth-of-type(3)')
369    })
370
371    it('toc is disabled by default', async () => {
372      // go to page serving markdown as text/markdown
373      await content.goto('http://localhost:3000/content-options-toc')
374      await content.bringToFront()
375      await content.waitForTimeout(300)
376
377      t.strictEqual(
378        await content.evaluate(() =>
379          document.querySelector('#_toc')
380        ),
381        null,
382        'toc should be disabled'
383      )
384    })
385
386    it('enable toc', async () => {
387      // enable toc
388      await popup.bringToFront()
389      // toc switch
390      await popup.click('.m-panel:nth-of-type(3) .m-switch:nth-of-type(3)')
391      // content auto reloads, but there is no way to have both tabs active
392      await content.bringToFront()
393      await content.reload()
394      await content.waitForTimeout(300)
395
396      t.deepStrictEqual(
397        await content.evaluate(() =>
398          Array.from(document.querySelectorAll('#_toc ._ul a'))
399            .map((a) => ({href: a.getAttribute('href'), text: a.innerText}))
400        ),
401        [
402          {href: '#h1', text: 'h1'},
403          {href: '#h2', text: 'h2'},
404          {href: '#h3', text: 'h3'},
405        ],
406        'toc should be rendered'
407      )
408    })
409  })
410
411  describe('set content options - scroll', () => {
412    before(async () => {
413      // popup
414      await popup.bringToFront()
415      // defaults button
416      await popup.click('button:nth-of-type(2)')
417      // content tab
418      await popup.click('.m-tabs a:nth-of-type(3)')
419    })
420
421    it('preserve scroll position by default', async () => {
422      // go to page serving markdown as text/markdown
423      await content.goto('http://localhost:3000/content-options-scroll')
424      await content.bringToFront()
425      await content.waitForTimeout(300)
426
427      // scroll down 200px
428      await content.evaluate(() =>
429        document.querySelector('html').scrollTop = 200
430      )
431      await content.waitForTimeout(300)
432
433      // reload page
434      await content.reload()
435      await content.waitForTimeout(300)
436
437      t.strictEqual(
438        await content.evaluate(() =>
439          document.querySelector('html').scrollTop,
440        ),
441        200,
442        'scrollTop should be 200px'
443      )
444    })
445
446    it('scroll to top', async () => {
447      // disable scroll option
448      await popup.bringToFront()
449      // scroll switch
450      await popup.click('.m-panel:nth-of-type(3) .m-switch:nth-of-type(2)')
451      // content auto reloads, but there is no way to have both tabs active
452      await content.bringToFront()
453      await content.reload()
454      await content.waitForTimeout(300)
455
456      t.strictEqual(
457        await content.evaluate(() =>
458          document.querySelector('html').scrollTop,
459        ),
460        0,
461        'scrollTop should be 0px'
462      )
463
464      // scroll down 200px
465      await content.evaluate(() =>
466        document.querySelector('html').scrollTop = 200
467      )
468      await content.waitForTimeout(300)
469
470      // reload page
471      await content.reload()
472      await content.waitForTimeout(300)
473
474      t.strictEqual(
475        await content.evaluate(() =>
476          document.querySelector('html').scrollTop,
477        ),
478        0,
479        'scrollTop should be 0px'
480      )
481    })
482
483    it('scroll to anchor', async () => {
484      // click on header link
485      await content.click('h2 a')
486      await content.waitForTimeout(300)
487
488      t.strictEqual(
489        await content.evaluate(() =>
490          document.querySelector('html').scrollTop + 1
491        ),
492        await content.evaluate(() =>
493          document.querySelector('h2').offsetTop
494        ),
495        'page should be scrolled to the anchor'
496      )
497
498      // scroll down 200px
499      await content.evaluate(() =>
500        document.querySelector('html').scrollTop += 200
501      )
502      await content.waitForTimeout(300)
503
504      t.strictEqual(
505        await content.evaluate(() =>
506          document.querySelector('html').scrollTop + 1
507        ),
508        await content.evaluate(() =>
509          document.querySelector('h2').offsetTop + 200
510        ),
511        'page should be scrolled below the anchor'
512      )
513
514      // reload page
515      await content.reload()
516      await content.waitForTimeout(300)
517
518      t.strictEqual(
519        await content.evaluate(() =>
520          document.querySelector('html').scrollTop
521        ),
522        await content.evaluate(() =>
523          document.querySelector('h2').offsetTop
524        ),
525        'page should be scrolled back to the anchor'
526      )
527    })
528  })
529
530  describe('set content options - autoreload', () => {
531    before(async () => {
532      // popup
533      await popup.bringToFront()
534      // defaults button
535      await popup.click('button:nth-of-type(2)')
536      // content tab
537      await popup.click('.m-tabs a:nth-of-type(3)')
538
539      await content.goto('about:blank')
540      await content.bringToFront()
541      await content.waitForTimeout(300)
542
543      // go to test page
544      await content.goto('http://localhost:3000/popup-autoreload')
545      await content.bringToFront()
546      await content.waitForTimeout(300)
547
548      // enable autoreload
549      await popup.bringToFront()
550      // autoreload switch
551      await popup.click('.m-panel:nth-of-type(3) .m-switch:nth-of-type(5)')
552      // content auto reloads, but there is no way to have both tabs active
553      await content.bringToFront()
554      await content.reload()
555      await content.waitForTimeout(300)
556
557      // TODO: wait for https://github.com/GoogleChrome/puppeteer/pull/2812
558      // update autoreload interval
559      // await content.evaluate(() => state.ms = 250)
560    })
561
562    it('test ajax autoreload with non UTF-8 encoding and inactive tab', async () => {
563      t.equal(
564        await content.evaluate(() =>
565          document.querySelector('#_html p').innerText.trim()
566        ),
567        '你好',
568        'first request'
569      )
570      // the initial interval is 1000
571      await content.waitForTimeout(1300)
572
573      t.equal(
574        await content.evaluate(() =>
575          document.querySelector('#_html p').innerText.trim()
576        ),
577        '你好',
578        'second request - xhr body is UTF-8 - should not trigger reload'
579      )
580      // the initial interval is 1000
581      await content.waitForTimeout(1300)
582
583      t.equal(
584        await content.evaluate(() =>
585          document.querySelector('#_html p').innerText.trim()
586        ),
587        '你好你好',
588        'third request - actual change'
589      )
590
591      // popup
592      await popup.bringToFront()
593      // the initial interval is 1000
594      await content.waitForTimeout(1300)
595      await content.bringToFront()
596      t.equal(
597        await content.evaluate(() =>
598          document.querySelector('#_html p').innerText.trim()
599        ),
600        '你好你好你好',
601        'fourth request - should reload inactive tab'
602      )
603    })
604  })
605
606}
607
Full Screen

containerManagerTestTest.js

Source: containerManagerTestTest.js Github

copy
1/*
2 * Copyright (C) 2013 salesforce.com, inc.
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({
17    browsers: ["-IE7","-IE8"],
18
19    testUseSharedContainer: {
20        attributes: {"useContainer": true},
21        test: [function(cmp) {
22            this.createPanels(5, cmp);
23        }, function(cmp) {
24            var containerManager = cmp.find("cm").getElement();
25            this.getPanelRefs(cmp).forEach(function(panel, index){
26                var panelEl = panel.getElement();
27
28                $A.test.assertEquals(containerManager, panelEl.parentNode,
29                    "Failed to match parentNode for panel id: " + panelEl.id);
30
31                $A.test.assertEquals((index+1), parseInt(panelEl.style.zIndex),
32                    "Incorrect z-index value for panel id: " + panelEl.id);
33            });
34        }]
35    },
36
37    testDoesNotUseSharedContainer: {
38        attributes: {"useContainer": false},
39        test: [function(cmp) {
40            this.createPanels(5, cmp);
41        }, function(cmp) {
42            var panelManager = cmp.find("pm").getElement();
43            this.getPanelRefs(cmp).forEach(function(panel, index){
44                var panelEl = panel.getElement();
45
46                $A.test.assertEquals(panelManager, panelEl.parentNode,
47                    "Failed to match parentNode for panel id: " + panelEl.id);
48
49                $A.test.assertEquals((index+1), parseInt(panelEl.style.zIndex),
50                    "Incorrect z-index value for panel id: " + panelEl.id);
51            });
52        }]
53    },
54
55    testDefaultZIndex: {
56        attributes: {"useContainer": true},
57        test: [function(cmp) {
58            this.createPanels(3, cmp);
59        }, function(cmp) {
60            this.verifyZIndices(this.getPanelRefs(cmp), ['1', '2', '3']);
61        }]
62    },
63
64    /**
65     * Verify that sendToBack/bringToFront accept component/element/id as arg
66     */
67    testAcceptableArgType: {
68        attributes: {"useContainer": true},
69        test: [function(cmp) {
70            this.createPanels(3, cmp);
71        }, function(cmp) {
72            var stackManager = this.getStackManager(cmp);
73            var panelRefs = this.getPanelRefs(cmp);
74
75            stackManager.bringToFront(panelRefs[0]);
76            this.verifyZIndices(this.getPanelRefs(cmp), ['4', '2', '3']);
77
78            stackManager.bringToFront(panelRefs[1].getElement());
79            this.verifyZIndices(this.getPanelRefs(cmp), ['4', '5', '3']);
80
81            stackManager.bringToFront(panelRefs[2].getGlobalId());
82            this.verifyZIndices(this.getPanelRefs(cmp), ['4', '5', '6']);
83        }]
84    },
85
86    testStackManager: {
87        attributes: {"useContainer": "true"},
88        test: [function(cmp) {
89            //initial   panel_id => zIndex
90            //panel_1 => 1  panelRefs[0]
91            //panel_2 => 2  panelRefs[1]
92            //panel_3 => 3  panelRefs[2]
93            //panel_4 => 4  panelRefs[3]
94            //panel_5 => 5  panelRefs[4]
95            this.createPanels(5, cmp);
96        }, function(cmp) {
97            var stackManager = this.getStackManager(cmp);
98            var panelRefs = this.getPanelRefs(cmp);
99            var length = panelRefs.length;
100
101            //after sendToBack
102            //reverse loop
103            //panel_5 => 5   =>sendToBack    0,1,2,3,4
104            //panel_4 => 4   =>sendToBack    0,1,2,3
105            //panel_3 => 3   =>sendToBack    0,1,2
106            //panel_2 => 2   =>sendToBack    0,1
107            //panel_1 => 1   =>sendToBack    0
108            panelRefs.slice(0,5).reverse().forEach(function(panel) {
109                var panelEl = panel.getElement();
110                stackManager.sendToBack(panelEl);
111            });
112            panelRefs.forEach(function(panel, index) {
113                var panelEl = panel.getElement();
114                $A.test.assertEquals(index, parseInt(panelEl.style.zIndex),
115                    "(sendToBack) Incorrect z-index value for panel id: " + panelEl.id);
116            });
117
118            //after bringToFront
119            //regular loop
120            //panel_1 => 1   =>bringToFront    5
121            //panel_2 => 2   =>bringToFront    5,6
122            //panel_3 => 3   =>bringToFront    5,6,7
123            //panel_4 => 4   =>bringToFront    5,6,7,8
124            //panel_5 => 5   =>bringToFront    5,6,7,8,9
125            panelRefs.forEach(function(panel) {
126                var panelEl = panel.getElement();
127                stackManager.bringToFront(panelEl);
128            });
129
130            panelRefs.forEach(function(panel, index) {
131                var panelEl = panel.getElement();
132                $A.test.assertEquals((index+length), parseInt(panelEl.style.zIndex),
133                    "(bringToFront) Incorrect z-index value for panel id: " + panelEl.id);
134            });
135        }, function(cmp) {
136            var panelRefs = this.getPanelRefs(cmp);
137            var panel_2 = panelRefs[1];
138
139            //delete panel_2 and assert newly assigned zIndexes
140            panel_2.destroy();
141
142            //1-5, 3-7, 4-8, 5-9
143            //after you destroy panel_2, z-indexes will get recomputed
144            //only if you call sendToBack or bringToFront
145            panelRefs.splice(1,1);
146            this.verifyZIndices(panelRefs, ['5', '7', '8', '9']);
147        }]
148    },
149
150    testGarbageCollection: {
151        attributes: {"useContainer": true},
152        test: [function(cmp) {
153            this.createPanels(5, cmp);
154        }, function () {
155            var queryString = $A.getQueryStatement().from("component")
156                .field("descriptor", "getDef().getDescriptor().toString()")
157                .groupBy("descriptor");
158            $A.test.assertEquals(5, queryString.query().groups['markup://ui:panel'].length, "Incorrect initial component count");
159        }, function(cmp) {
160            var containerManager = cmp.find("cm");
161            var queryString = $A.getQueryStatement().from("component")
162                .field("descriptor", "getDef().getDescriptor().toString()")
163                .groupBy("descriptor");
164
165            //destroy container manager
166            containerManager.destroy();
167
168            var actual = queryString.query().groups['markup://ui:panel'];
169            $A.test.assertUndefined(actual, "Failed to destroy the panels contained in containerManager");
170        }]
171    },
172
173    /**
174     * Verify new panel zIndex is based on existing panel's largest zIndex
175     */
176    testNewPanelZIndexBasedOnPrevPanels: {
177        attributes: {"useContainer": true},
178        test: [function(cmp) {
179            this.createPanels(2, cmp);
180        }, function(cmp) {
181            // create 1 more after modifying the first one's zIndex
182            var panelRefs = this.getPanelRefs(cmp);
183            panelRefs[0].getElement().style.zIndex = 1000;
184            this.createPanels(1, cmp);
185        }, function(cmp) {
186            this.verifyZIndices(this.getPanelRefs(cmp), ['1000', '2', '1001']);
187        }]
188    },
189
190    /**
191     * Verify destroyPanel event destroys panel
192     */
193    testDestroyPanel: {
194        attributes: {"useContainer": true},
195        test: [function(cmp) {
196            this.createPanels(5, cmp);
197        }, function(cmp) {
198            var panelRefs = this.getPanelRefs(cmp);
199
200            $A.test.assertTrue(panelRefs[0].isValid());
201
202            this.destroyPanel(panelRefs[0]);
203
204            $A.test.assertFalse(panelRefs[0].isValid());
205            $A.test.assertEquals(4, this.getPanelCount());
206        }]
207    },
208
209    /****************************************************************
210     ********************* Helper Functions *************************
211     ****************************************************************/
212    getStackManager: function(cmp) {
213        return cmp.getDef().getHelper().smLib.stackManager;
214    },
215
216    getPanelRefs: function(cmp) {
217        return cmp.getDef().getHelper().globalPanelRefs;
218    },
219
220    getPanelCount: function() {
221        return $A.test.select(".uiPanel").length;
222    },
223
224    createPanels: function(count, cmp) {
225        var expectedCount = $A.test.select(".uiPanel").length + count;
226
227        var button = cmp.find("create").getElement();
228        var i = 1;
229        while(i <= count) {
230            button.click();
231            i++;
232        }
233
234        var self = this;
235        $A.test.addWaitForWithFailureMessage(true, function() {
236            return (self.getPanelCount() === expectedCount);
237        }, "Failed to create panels.");
238    },
239
240    destroyPanel: function(panel) {
241        $A.get('e.ui:destroyPanel').setParams({
242            panelInstance: panel
243        }).fire();
244    },
245
246    verifyZIndices: function(panelRefs, expectedZIndices) {
247        for(var i = 0; i < panelRefs.length; i++) {
248            var panelEl = panelRefs[i].getElement();
249            $A.test.assertEquals(parseInt(expectedZIndices[i]), parseInt(panelEl.style.zIndex),
250                "Incorrect zIndex for panel id:" + panelEl.id
251            );
252        }
253    }
254})
255
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)