Skip to content

Instantly share code, notes, and snippets.

@sillicon
Last active Nov 27, 2020
Embed
What would you like to do?
Screen Capture a single webElement, not the whole page in JavaScript, Selenium
const webdriver = require('selenium-webdriver'),
By = webdriver.By,
until = webdriver.until;
const fs = require("fs");
function takeScreenshot(driver, webElement, imagePath) { // driver -> webDriver; webElement -> WebElement; imagePath -> physical path to save the image
var base64Data = "";
var location = {};
var bulk = [];
driver.then(_ => {
webElement.getLocation().then(e => {
location.x = e.x;
location.y = e.y;
});
webElement.getSize().then(e => {
location.height = e.height;
location.width = e.width;
});
driver.manage().window().getSize().then(e => {
location.browserHeight = e.height;
location.broserWidth = e.width;
});
}).then(_ => {
driver.takeScreenshot().then(data => {
base64Data = data.replace(/^data:image\/png;base64,/, "");
});
}).then(_ => {
const sizeLimit = 700000; // around 700kb
const imgSize = base64Data.length;
driver.executeScript(() => {
window.temp = new Array;
}).then(_ => {
for (var i = 0; i < imgSize; i += sizeLimit) {
bulk.push(base64Data.substring(i, i + sizeLimit));
}
bulk.forEach((element, index) => {
driver.executeScript(() => {
window.temp[arguments[0]] = arguments[1];
}, index, element);
});
});
}).then(_ => {
driver.executeScript(() => {
var tempBase64 = window.temp.join("");
var image = new Image();
var location = arguments[0];
image.src = "data:image/png;base64," + tempBase64;
image.onload = function () {
var canvas = document.createElement("canvas");
canvas.height = location.height;
canvas.width = location.width;
canvas.style.height = location.height + 'px';
canvas.style.width = location.width + 'px';
var ctx = canvas.getContext('2d');
ctx.drawImage(image, -location.x, -location.y);
window.canvasData = canvas.toDataURL();
window.temp = [];
}
}, location);
}).then(_ => {
return driver.executeScript(() => {
var data = window.canvasData;
window.canvasData = "";
return data;
}).then(data => {
var tempData = data.replace(/^data:image\/png;base64,/, "");
fs.writeFileSync(imagePath, tempData, "base64");
console.log("Image capture complete");
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment