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

CodeGym DARKMODE.user.js

Source: CodeGym DARKMODE.user.js Github

copy
1// ==UserScript==
2// @name         CodeGym DARKMODE
3// @namespace    http://tampermonkey.net/
4// @version      0.2.2
5// @description  add style for quiz table.generaltable ; .que .content 20022022
6// @author       C1221G1-NguyenTranThanhNghia @iamnotnghia
7// @website      https://github.com/dodooh
8// @match        https://james.codegym.vn/*
9// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
10// @grant        none
11// @run-at       document-idle
12// @license      MIT
13// ==/UserScript==
14
15function addStyleTag(css) {
16    var head, style;
17    head = document.getElementsByTagName('head')[0];
18    if (!head) { return; }
19    style = document.createElement('style');
20    style.type = 'text/css';
21    style.innerHTML = css;
22    head.appendChild(style);
23}
24// h1 : 36px;
25// h2 : 32px;
26// h3 : 24px;
27
28// keyframe rainbow
29addStyleTag('@keyframes rainbow {   0%{background-position:left}  50%{background-position:right}  100%{background-position:left}}')
30// LOGO filter
31addStyleTag('span.navbar-brand-logo.mini {filter: grayscale(75%);}')
32// body bg
33addStyleTag('#page, .main-navigation ul ul{background: #202225 !important;}')
34addStyleTag('.navbar .navbar-brand ,.navbar.nav-inverse, .bg-primary{background: #3a4044 !important;}')
35addStyleTag('body {color: #ACC8E5 !important; background: #112A46 !important;font-family: \'Montserrat\', Arial, sans-serif !important; }')
36// dropdown-menu
37addStyleTag('.dropdown-menu {background: #202225 !important; color: #83ba52 !important; }')
38// h1 neon
39addStyleTag('h1,h2,h3,h4 {letter-spacing: 0.02em !important;text-transform: uppercase !important;text-shadow: 0 0 0.15em #1da9cc !important;white-space: nowrap !important;filter: blur(0.007em) !important;}')
40addStyleTag('h1 {font-weight: 700; font-size: 36px; color: #83ba52; }')
41addStyleTag('h2 {font-weight: 600; font-size: 28px; color: #fff;')
42addStyleTag('h3 {font-weight: 500; font-size: 24px; color: #fff;}')
43addStyleTag('h4 {font-weight: 400; font-size: 20px; color: #fff;}')
44addStyleTag('h1.page-title.font-size-24.mb-0, a.nav-link.navbar-avatar > span.username  {text-shadow:none;font-size:2.0rem!important;color: white; text-shadow: 0 0 0.05em #fff, 0 0 0.2em #fe05e1, 0 0 0.3em #fe05e1!important;} a.nav-link.navbar-avatar > span.username {font-weight:bold !important;text-transform:uppercase;font-size:1rem !important;} span.avatar{box-shadow:0 0 0.05em #fff, 0 0 0.2em #fe05e1, 0 0 0.3em #fe05e1!important;}')
45// .pagelayout-course .course-content .sectionname a {
46addStyleTag('.pagelayout-course .course-content .sectionname a { color: #83ba52 !important; font-weight: 600;letter-spacing: 0.02em !important;text-transform: uppercase !important;text-shadow: 0 0 0.15em #1da9cc !important;white-space: nowrap !important;filter: blur(0.007em) !important;}')
47// left side nav
48addStyleTag('#nav-drawer-container, [data-region="drawer"] .list-group-item.active {background:#3a4044;}')
49addStyleTag('.list-group-item-action, .list-group-item {color: #B1FF91 !important;background:#3a4044 !important;text-shadow: 0 0 0.15em #1da9cc;white-space: nowrap !important;}')
50addStyleTag('.list-group-item span.media-body,  {color: #fff !important;text-shadow:none;}')
51addStyleTag('.list-group-item > a > span.instancename {font-size: 12px !important;}')
52addStyleTag('[data-region="drawer"] .site-menubar-footer a {background:#3a4044 !important;} [data-region="drawer"] .site-menubar-footer a .fa{color:#B1FF91 !important;}')
53addStyleTag('#activity-nav .list-group-item a {  padding: 8px 16px; }')
54//h3.section-title
55addStyleTag('h3.section-title {font-weight: 600;font-size: 32px;color: #fff !important;letter-spacing: 0.02em !important;text-shadow: 0 0 0.15em #1da9cc !important;white-space: nowrap !important;}')
56addStyleTag('h3.section-title>a:hover {text-decoration: none;}')
57// ul.section li
58addStyleTag('ul.section > li {border-bottom: 1px #f8edeb solid;} ')
59// code
60addStyleTag('code {font-family: SFMono-Regular,Consolas, Arial, sans-serif;font-weight: bold ;background: #666;border-radius: 0.5em;white-space: pre;font-size: 16px!important;line-height: 1.75;}')
61addStyleTag('.hljs {color: #fff}')
62addStyleTag('span.hljs-keyword, span.hljs-number, span.hljs-string {color: #83ba52;}')
63// [role="main"] TITLE
64//background: linear-gradient(to right, crimson,pink,springgreen);
65addStyleTag(' [role="main"] > h2 {filter:none !important;text-shadow: none !important; font-size: 32px; background: linear-gradient(to right, #A2D2FF,#272882,#FF865E,#FEE440);  background-size: 200% 200%;  animation: rainbow 10s ease-in-out infinite;  background-clip: text;  -webkit-background-clip:text;  color:rgba(0,0,0,0);   display:block;  text-align:center;  transition: color .2s ease-in-out;  text-transform:uppercase;  font-weight:900;}')
66// card bg
67addStyleTag('.pagelayout-course .course-content .section.main,.card, .pagelayout-course #section-0 {background: #262a2d !important;}')
68addStyleTag('.hljs {background: #1b1b1b !important;}')
69// check-box size
70addStyleTag('.icon {width: 20px !important;height: 20px}')
71// .instancename title
72addStyleTag(' .instancename {font-size: 16px!important; color: rgba(255, 255, 255, 0.8) !important;text-shadow: 0 0 0.10em #1da9cc !important;white-space: nowrap !important;filter: blur(0.007em) !important;}')
73addStyleTag(' .instancename:hover {font-size: 18px!important;color: rgba(255, 255, 255, 1);text-shadow: 0 0 0.2em #1da9cc;transition: font-size 0.4s ease;}')
74addStyleTag(' .activityinstance>a:hover {text-decoration: none;}')
75// a:link a:hover
76addStyleTag('a:link{color: #fff important;} a:hover {color: #82d4f0;')
77//.activity-count
78addStyleTag('.course-content .section-summary .section-summary-activities .activity-count {color:#6db467 !important;}')
79// question quiz
80addStyleTag('.que .content {background: #26343f;} .que .qtext {    font-size: 1.25rem;background: #314250;} [data-region="blocks-column"], .bg-white {background: #3a4044 !important;} .nav-tabs .nav-link.active .fa {    color: #7eb654!important;}')
81// nav
82addStyleTag('.nav-tabs .nav-link { color: #5a6970!important;}')
83// table
84addStyleTag('table, table.generaltable {text-align: left; overflow: hidden; margin: 0 auto;  display: table; padding: 0 0 8em 0;} tr:nth-child(odd) { background-color: #323C50; } tr:nth-child(even) { background-color: #2C3446; } td:first-child { color: #FB667A; }')
85addStyleTag('table.generaltable tr:nth-child(odd) {color:white; background-color: #277231  !important; } table.generaltable tr:nth-child(even) {color:white; background-color: #305621  !important; } table.quizreviewsummary td.cell,table.quizreviewsummary th.cell {color:inherit;background-color: inherit !important;}')
86addStyleTag('tr.bestrow td {color: black !important; font-weight: 600 !important; font-size:1.15rem !important} tr.lastrow td {color: black !important;}')
87// select id="jump-to-activity"
88// ResetStyle
89addStyleTag('#jump-to-activity.custom-select {  appearance: none;  outline: 0;  border: 0; box-shadow: none; flex: 1; padding: 0 1em; color: #fff; background-color: #2c3e50; background-image: none; cursor: pointer;}')
90/* Remove IE arrow */
91addStyleTag('#jump-to-activity.custom-select::-ms-expand {   display: none; }')
92/* Custom Select wrapper */
93addStyleTag('#jump-to-activity.custom-select{ position: relative;  display: flex;   width: 20em;  height: 3em;  border-radius: .25em;  overflow: hidden;}')
Full Screen

content.js

Source: content.js Github

copy
1/*
2 * content function
3 *
4 * Example invocation:
5 *
6 * content({
7 *  page: await browser.newPage(),
8 *  context: {
9 *    url: 'https://example.com',
10 *  },
11 * });
12 *
13 * @param args - object - An object with a puppeteer page object, and context.
14 * @param args.page - object - Puppeteer's page object (from await browser.newPage)
15 * @param args.context - object - An object of parameters that the function is called with. See src/schemas.ts
16 */
17module.exports = async function content ({ page, context }) {
18  const {
19    addScriptTag = [],
20    addStyleTag = [],
21    authenticate = null,
22    url = null,
23    html,
24    gotoOptions,
25    rejectRequestPattern = [],
26    requestInterceptors = [],
27    cookies = [],
28    setExtraHTTPHeaders = null,
29    setJavaScriptEnabled = null,
30    userAgent = null,
31    waitFor,
32  } = context;
33
34  if (authenticate) {
35    await page.authenticate(authenticate);
36  }
37
38  if (setExtraHTTPHeaders) {
39    await page.setExtraHTTPHeaders(setExtraHTTPHeaders);
40  }
41
42  if (setJavaScriptEnabled !== null) {
43    await page.setJavaScriptEnabled(setJavaScriptEnabled);
44  }
45
46  if (rejectRequestPattern.length || requestInterceptors.length) {
47    await page.setRequestInterception(true);
48    page.on('request', (req) => {
49      if (rejectRequestPattern.find((pattern) => req.url().match(pattern))) {
50        return req.abort();
51      }
52      const interceptor = requestInterceptors
53        .find(r => req.url().match(r.pattern));
54      if (interceptor) {
55        return req.respond(interceptor.response);
56      }
57      return req.continue();
58    });
59  }
60
61  if (cookies.length) {
62    await page.setCookie(...cookies);
63  }
64
65  if (userAgent) {
66    await page.setUserAgent(userAgent);
67  }
68
69  if (url !== null) {
70    await page.goto(url, gotoOptions);
71  } else {
72    // Whilst there is no way of waiting for all requests to finish with setContent,
73    // you can simulate a webrequest this way
74    // see issue for more details: https://github.com/GoogleChrome/puppeteer/issues/728
75
76    await page.setRequestInterception(true);
77    page.once('request', request => {
78      request.respond({ body: html });
79      page.on('request', request => request.continue());
80    });
81
82    await page.goto('http://localhost', gotoOptions);
83  }
84
85  if (addStyleTag.length) {
86    for (tag in addStyleTag) {
87      await page.addStyleTag(addStyleTag[tag]);
88    }
89  }
90
91  if (addScriptTag.length) {
92    for (script in addScriptTag) {
93      await page.addScriptTag(addScriptTag[script]);
94    }
95  }
96
97  if (waitFor) {
98    if (typeof waitFor === 'string') {
99      const isSelector = await page.evaluate((s) => {
100        try { document.createDocumentFragment().querySelector(s); }
101        catch (e) { return false; }
102        return true;
103      }, waitFor);
104
105      await (isSelector ? page.waitFor(waitFor) : page.evaluate(`(${waitFor})()`));
106    } else {
107      await page.waitFor(waitFor);
108    }
109  }
110
111  const data = await page.content();
112
113  return {
114    data,
115    type: 'html'
116  };
117};
118
Full Screen

grabber.js

Source: grabber.js Github

copy
1const puppeteer = require('puppeteer');
2const argv = require('minimist')(process.argv.slice(2));
3
4const url = argv.url;
5const outdir = argv.outdir || '.';
6if (url.includes('.com')) {
7    offset = url.indexOf('.com');
8} else if (url.includes('.net')) {
9    offset = url.indexOf('.net');
10} else {
11    offset = 3;
12}
13
14let filename = url.substring(offset + 5).replace(/\//g,'-');
15
16if (filename.endsWith('.php')) {
17    filename = filename.slice(0,-4);
18}
19
20if (filename.endsWith('-')) {
21    filename = filename.slice(0,-1);
22}
23
24async function timeout(ms) {
25  return new Promise(resolve => setTimeout(resolve, ms));
26}
27
28(async () => {
29    const browser = await puppeteer.launch({ignoreHTTPSErrors:true});
30    const page = await browser.newPage();
31
32    await page.setUserAgent('gothamgrabber (a project of freedom.press)');
33
34    await page.setJavaScriptEnabled(true);
35
36    await page.emulateMedia('screen');
37
38    try {
39        const res = await page.goto(url, {timeout: 60000, waitUntil:'networkidle2'});//{timeout:30000});
40        if (res.ok() !== true) {
41            console.log('Server returned status code ' + res.status());
42            process.exitCode = 1;
43            await browser.close();
44            return;
45        }
46    } catch (e) {
47        console.log(e);
48        process.exitCode = 1;
49        await browser.close();
50        return;
51    }
52
53    let pdf_options = {displayHeaderFooter: true, margin: {top: '.75in', bottom: '.75in', left: '.5in', right: '.5in'}, printBackground: true, path: outdir + '/' + filename + '.pdf'}
54
55    if (url.includes('dnainfo.com')) {
56        await page.addStyleTag({path: 'tweaks/dnainfo.css'})
57    }
58
59    if (url.includes('laweekly.com')) {
60        await page.setViewport({width: 500, height: 800})
61        pdf_options.scale = .75;
62        pdf_options.printBackground = false;
63        await page.addStyleTag({path: 'tweaks/laweekly.css'})
64    }
65
66    if (url.includes('the-toast.net')) {
67        await page.addStyleTag({path: 'tweaks/thetoast.css'})
68		await page.setViewport({width:500, height:600});
69    }
70
71    if (url.includes('newsweek.com')) {
72        await page.addStyleTag({path: 'tweaks/newsweek.css'});
73        await page.setViewport({width:500, height: 600});
74        pdf_options.scale = .75;
75    }
76
77    if (argv.k) {
78        await page.addStyleTag({path: 'tweaks/kinja.css'});
79        await page.setViewport({width:500, height: 600});
80    }
81
82    const height = await page.evaluate(() => document.documentElement.scrollHeight);
83
84    const viewportHeight = await page.viewport().height;
85    let viewportIncr = 0;
86
87    while (viewportIncr + viewportHeight < height - 1000) {
88        await page.evaluate(_viewportHeight => {
89            window.scrollBy(0, _viewportHeight);
90            console.log(_viewportHeight);
91        }, viewportHeight);
92        await timeout(1000);
93        viewportIncr = viewportIncr + viewportHeight;
94    }
95    await timeout(3000);
96
97    try {
98    await page.pdf(pdf_options);
99    } catch (e) {
100        console.log(e);
101        process.exitCode = 1;
102        await browser.close();
103        return;
104    }
105
106    await browser.close();
107})();
108
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)