PhantomJS clickOn + waitForElem helpers
posted on November 2, 2015, 3:48 pm in
Here are some helper functions to use with PhantomJS for common testing functionality.
The clickOn(querySelector, cb) function provides an easy way to click on any element on the page using only a document.querySelector().
The waitForElem(querySelector, cb) function provides a way to wait for an element to exists, again using a document.querySelector().
the code
/*
* phantom-helpers.js (Nov 2, 2015)
* Copyright 2015, http://codeeverywhere.ca
* Licensed under the MIT license.
* This helper function Module (includes 'clickOn' and 'waitForElemExists')
*/
module.exports = function() {
this.clickOn = function(querySelector, cb) {
// Get element position
var pos = page.evaluate(function(query) {
try {
return document.querySelector(query).getBoundingClientRect();
} catch (e) {
return false;
}
}, querySelector);
// If failed, return error
if (pos === false) {
cb(false, "Error with " + querySelector);
// else, do click
} else {
page.sendEvent("click", pos.left + 1, pos.top + 1);
cb(pos, false);
}
};
this.waitingForElem = 0;
this.waitForElemExists = function(querySelector, cb) {
var maxLoops = 25;
var timer;
waitingForElem++;
timer = setInterval(function() {
var elemEval = page.evaluate(function(query) {
try {
return document.querySelector(query);
} catch (e) {
return false;
}
}, querySelector);
// empty string?
if (typeof elemEval == "string" && elemEval.length === 0)
elemEval = false;
if (typeof elemEval == "object" && elemEval.innerText.length === 0)
elemEval = false;
// null?
if (elemEval === null)
elemEval = false;
if (elemEval !== false || maxLoops === 0) {
clearInterval(timer);
waitingForElem--;
if (maxLoops === 0) {
cb({
innerText: ""
}, "tries exhusted for " + querySelector);
} else {
cb(elemEval, false);
}
}
maxLoops--;
}, 250);
};
};
Create a new file phantom-helpers.js and include it in your Node.js script with require('./phantom-helpers')().
sample usage with PhantomJS
var page = require('webpage').create();
require('./phantom-helpers')();
// Page click
clickOn('.className', function(pos, err) {
if (err) console.log("err=", err);
});
// Page click + keyboard input
clickOn('.className', function(pos, err) {
if (err) console.log("err=", err);
page.sendEvent('keypress', "some text...");
});
// Waiting for an element to exists
waitForElemExists("#someElemId", function(elem, err) {
if (err) console.log("err=", err);
var text = elem.innerText.trim();
});