10 examples of 'javascript take screenshot of current page' in JavaScript

Every line of 'javascript take screenshot of current page' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
48export function screenShot (window) {
49 if (window) {
50 window.webContents.capturePage((image) => {
51 let opts = {
52 title: 'Save Screen Shot',
53 defaultPath: app.getPath('documents'),
54 filters: [
55 {name: 'PNG', extensions: ['png']},
56 {name: 'JPG', extensions: ['jpg']}
57 ]
58 }
59 let cb = (path) => {
60 if (path) {
61 let png = S(path.toLowerCase()).endsWith('png')
62
63 let buf = png ? image.toPNG() : image.toJPEG(100)
64 fs.writeFile(path, buf, 'binary', (wError) => {
65 if (wError) {
66 dialog.showErrorBox("Something went wrong :'(", 'Screen shot could not be saved to that path')
67 } else {
68 dialog.showMessageBox(window, {
69 type: 'info',
70 title: 'Done',
71 message: 'Screen shot saved',
72 buttons: ['Ok']
73 }, (r) => console.log(r))
74 }
75 })
76 }
77 }
78 dialog.showSaveDialog(window, opts, cb)
79 })
80 }
81}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

215function takeScreenshot(element) {
216 if (!url.value) {
217 onEmptyUrl();
218 return;
219 }
220
221 var httpRegex = /(http(s?))\:\/\//gi;
222
223 if (!httpRegex.test(url.value)) {
224 url.value = 'https://' + url.value;
225 }
226
227 element.classList.add('loading');
228 document.querySelector('progress-bar').removeAttribute('hidden');
229 window.location.href += `screenshot/${encodeUrl(url.value)}?width=${window.innerWidth}&height=${window.innerHeight}`;
230}
83function takeScreenshot(driver) {
84 return GalenUtils.takeScreenshot(driver);
85}
41public async generateScreenshot(pageContent: string): Promise<PNG> {
42 let page: Page | undefined;
43
44 try {
45 const browser = await this._browserPromise;
46 page = await browser.newPage();
47
48 const errors: string[] = [];
49 page.on('pageerror', (error: Error) => {
50 errors.push(error.message);
51 });
52
53 page.on('response', (response: Response) => {
54 if (!response.ok()) {
55 errors.push(`Network error: ${response.url()} status=${response.status()}`);
56 }
57 });
58
59 await page.setContent(pageContent, { waitUntil: 'load' });
60
61 // to avoid random cursor position
62 await page.mouse.move(viewportWidth / 2, viewportHeight / 2);
63
64 // wait for test case is ready
65 await page.evaluate(() => {
66 // tslint:disable-next-line:no-any
67 return (window as any).testCaseReady;
68 });
69
70 // let's wait until the next af to make sure that everything is repainted
71 await page.evaluate(() => {
72 return new Promise((resolve: () => void) => {
73 window.requestAnimationFrame(() => {
74 // and a little more time after af :)
75 setTimeout(resolve, 50);
76 });
77 });
78 });
79
80 if (errors.length !== 0) {
81 throw new Error(errors.join('\n'));
82 }
83
84 return PNG.sync.read(await page.screenshot({ encoding: 'binary' }));
85 } finally {
86 if (page !== undefined) {
87 await page.close();
88 }
89 }
90}
60async takeScreenshot(selector) {
61 let rect = {}
62 if (selector) rect = await this.evaluate(`document.body.querySelector('${selector}').getBoundingClientRect()`)
63 const { data } = await this.Page.captureScreenshot({
64 clip: { ...rect, scale: 1 },
65 })
66 const screenshot = new Buffer(data, 'base64')
67 return screenshot
68}
61function takeScreenshot(errorObj, callback) {
62 window.html2canvas(document.body, {
63 onrendered: function (canvas) {
64 try {
65 errorObj.screenshot = canvas.toDataURL("image/png");
66 callback(errorObj);
67 } catch (e) {
68 console.log("Error in error handler!");
69 console.log(e);
70 callback(errorObj);
71 }
72 }
73 });
74}
142async screenshot(
143 url: string,
144 isMobile: boolean,
145 dimensions: ViewportDimensions,
146 options?: object): Promise<Buffer> {
147 const page = await this.browser.newPage();
148
149 page.setViewport(
150 {width: dimensions.width, height: dimensions.height, isMobile});
151
152 if (isMobile) {
153 page.setUserAgent(MOBILE_USERAGENT);
154 }
155
156 await page.goto(url, {timeout: 10000, waitUntil: 'networkidle0'});
157
158 // Must be jpeg & binary format.
159 const screenshotOptions =
160 Object.assign({}, options, {type: 'jpeg', encoding: 'binary'});
161 const buffer = await page.screenshot(screenshotOptions);
162 return buffer;
163}
228async screenshot(options = {}) {
229 let needsViewportReset = false;
230
231 let boundingBox = await this.boundingBox();
232 assert(boundingBox, 'Node is either not visible or not an HTMLElement');
233
234 const viewport = this._page.viewport();
235
236 if (boundingBox.width > viewport.width || boundingBox.height > viewport.height) {
237 const newViewport = {
238 width: Math.max(viewport.width, Math.ceil(boundingBox.width)),
239 height: Math.max(viewport.height, Math.ceil(boundingBox.height)),
240 };
241 await this._page.setViewport(Object.assign({}, viewport, newViewport));
242
243 needsViewportReset = true;
244 }
245
246 await this._scrollIntoViewIfNeeded();
247
248 boundingBox = await this.boundingBox();
249 assert(boundingBox, 'Node is either not visible or not an HTMLElement');
250
251 const { layoutViewport: { pageX, pageY } } = await this._client.send('Page.getLayoutMetrics');
252
253 const clip = Object.assign({}, boundingBox);
254 clip.x += pageX;
255 clip.y += pageY;
256
257 const imageData = await this._page.screenshot(Object.assign({}, {
258 clip
259 }, options));
260
261 if (needsViewportReset)
262 await this._page.setViewport(viewport);
263
264 return imageData;
265}
78async function takeScreenshot(page, fullPage, fileUrl, desc, isExpected, minor) {
79 let screenshotName = testNameFromFile(fileUrl);
80 if (desc) {
81 screenshotName += '-' + slugify(desc, { replacement: '-', lower: true });
82 }
83 if (minor) {
84 screenshotName += '-' + minor;
85 }
86 let screenshotPrefix = isExpected ? 'expected' : 'actual';
87 fse.ensureDirSync(path.join(__dirname, getScreenshotDir()));
88 let screenshotPath = path.join(__dirname, `${getScreenshotDir()}/${screenshotName}-${screenshotPrefix}.png`);
89 await page.screenshot({
90 path: screenshotPath,
91 fullPage
92 });
93
94 return {screenshotName, screenshotPath};
95}
3function takeScreenshot(path, image) {
4
5 fs.access(path, fs.F_OK, (err) => {
6 if (err) {
7 console.info("File path doesn't exists ... Let's create!")
8 fs.mkdir(path, {recursive: true}, err => {})
9 }
10 // file exists
11 browser.saveScreenshot(path + image)
12 })
13}

Related snippets