This repository has been archived by the owner on Feb 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
savefullScreenShot.js
218 lines (210 loc) · 7.96 KB
/
savefullScreenShot.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
const path = require('path');
const fs = require('fs');
const imageMerge = require('merge-img');
/**
* Create and save a full-page 'screen' capture.
*
* @param {string} namePrefix
* Prefix for the file name, optional.
* @param {string} nameSuffix
* Suffix for the file name, optional.
* @param {string} name
* Test name override.
* @param {bool} override
* Whether the destionation can be overridden if exists. True by default.
* @param {bool} pieceShots
* Create 'normal' screenshots. False by default.
*
* @return {object}
* The 'browser' instance.
*/
exports.command = function savefullScreenShot(
namePrefix = '',
nameSuffix = '',
name = '',
override = (typeof this.globals.fullScreenShotOverride !== 'undefined' ?
this.globals.fullScreenShotOverride : true),
pieceShots = (typeof this.globals.fullScreenShotPieces !== 'undefined' ?
this.globals.fullScreenShotPieces : false),
) {
const _self = this;
const platformName = _self.capabilities.platformName || _self.capabilities.platform || 'nan';
const browserName = _self.capabilities.browserName || 'nan';
let nameComponents = [(name ? name : _self.currentTest.name), platformName, browserName];
if (
_self.capabilities.mobileEmulationEnabled &&
_self.options.desiredCapabilities.chromeOptions &&
_self.options.desiredCapabilities.chromeOptions.mobileEmulation &&
_self.options.desiredCapabilities.chromeOptions.mobileEmulation.deviceName) {
nameComponents.push(_self.options.desiredCapabilities.chromeOptions.mobileEmulation.deviceName.replace(/\s/g, '').replace(/\//g, ''));
}
if (namePrefix) {
nameComponents.unshift(namePrefix);
}
if (nameSuffix) {
nameComponents.push(nameSuffix);
}
const fileName = nameComponents.join('--').replace(/\s/g, '-');
let fileNameWithPath = [(this.options && this.options.screenshotsPath ?
this.options.screenshotsPath : 'screenshots'), this.currentTest.module.split(path.sep).pop(), fileName].join(path.sep);
if (!override && fs.existsSync(fileNameWithPath + '.png')) {
let index = 0;
while (fs.existsSync(`${fileNameWithPath}_${index}.png`)) {
index++;
}
fileNameWithPath += `_${index}`;
}
// Common storage.
let initialScrollPos = {};
let windowDimensions = {};
let documentDimensions = {};
let viewportDimensions = {};
let windowHandle;
const documentElementTag = platformName === 'iOS' ? 'body' : 'html';
// For first, we get dimensions of the document, viewPort and browser window, and
// create 'real' screenshots (piece by piece) about the page.
this
// Get html element's size.
.getElementSize(documentElementTag, (htmlSizeResult) => {
if (!htmlSizeResult.errorStatus) {
documentDimensions = htmlSizeResult.value;
}
})
// Get window handle (id of the api window).
.windowHandle((windowHandleResult) => {
if (!windowHandleResult.errorStatus) {
windowHandle = windowHandleResult.value;
}
})
// Get browser window size.
.perform(() => {
this.windowSize(windowHandle, (windowSizeResult) => {
if (!windowSizeResult.errorStatus) {
windowDimensions = windowSizeResult.value;
}
})
})
// Get dimensions of the viewport.
.execute(
function () {
// Return actual viewPort dimensions.
return {
width: Math.max(document.documentElement.clientWidth, (window.innerWidth || 0)),
height: Math.max(document.documentElement.clientHeight, (window.innerHeight || 0))
};
},
[],
function (viewportSizeResult) {
viewportDimensions = viewportSizeResult.value;
}
)
// Get initial scroll position.
.execute(
function () {
// Return actual scroll position difference.
return {
x: ((window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0)),
y: ((window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0))
};
},
[],
function (initialScrollPosResult) {
initialScrollPos = !initialScrollPosResult.errorStatus ? initialScrollPosResult.value : {};
}
)
// Create 'normal' screenshots.
// - capturing viewport from top (Y = 0)
// - scroll to Y += viewport height
// - continue this until bottom of the page reached.
.perform(() => {
if (pieceShots) {
const steps = Math.ceil(documentDimensions.height / viewportDimensions.height);
let shotSet = [];
let offsetY = 0;
this.perform(() => {
Array.from(Array(steps).keys()).forEach(function(step) {
this
.execute(
function () {
// Scroll.
window.scroll(0, arguments[0]);
// Return actual scroll position difference.
return arguments[0] - ((window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0));
},
[(step * viewportDimensions.height)],
function (diff) {
offsetY = !diff.errorStatus ? diff.value : 0;
}
)
.pause(50)
.perform(() => {
const src = path.join(fileNameWithPath, `${step + 1}--${viewportDimensions.width}x${viewportDimensions.height}--${offsetY}.png`);
shotSet.push({
src: src,
offsetY: offsetY
});
this.saveScreenshot(src);
});
}, this);
// We wound merge images here, but Nightwatch cannot handle promises
// right now.
// })
// .perform(() => {
// // Merge shot pieces.
// console.log(`Attempt to write ${fileNameWithPath}.png`);
// imageMerge(shotSet, { direction: true }).then((fullShot) => {
// // Save image as file
// fullShot.write(fileNameWithPath + '.png', () => {
// // Remove stale shot pieces and their directory.
// shotSet.forEach((item) => {
// fs.unlinkSync(item.src);
// });
// fs.rmdirSync(fileNameWithPath);
// console.log(`Written ${fileNameWithPath}.png`);
// });
// }).catch((err) => {
// console.log(err);
// });
// this.pause(5000); // Give some time for Jimp to merge and write image.
})
.execute(function () {
// Scroll back to the initial position.
window.scroll(arguments[0], arguments[1]);
}, [initialScrollPos.x, initialScrollPos.y]);
}
})
// Try to create a singe full page screenshot by resizing the whole browser
// window. This does not work for mobile devices like iOS or Android
// (makes sense by the way).
.perform(() => {
if (!pieceShots && windowDimensions.height) {
// Resize the browser window to make document fit into.
this.resizeWindow(
Math.floor(
documentDimensions.width +
// Add diff between the viewPort and window width.
(windowDimensions.width - viewportDimensions.width)
),
Math.floor(
documentDimensions.height +
// Add diff between the viewPort and window height.
(windowDimensions.height - viewportDimensions.height)
),
() => {
this.saveScreenshot(fileNameWithPath + '.png');
}).perform(() => {
// Restore original window dimensions.
if (windowDimensions.width && windowDimensions.height) {
this
.resizeWindow(windowDimensions.width, windowDimensions.height)
.execute(function () {
// Scroll to initial.
window.scroll(arguments[0], arguments[1]);
}, [initialScrollPos.x, initialScrollPos.y]);
}
});
}
})
.pause(1);
return this;
};