view release on metacpan or search on metacpan
lib/WWW/Mechanize/PhantomJS.pm view on Meta::CPAN
This is WWW::Mechanize::PhantomJS specific.
=cut
sub document {
$_[0]->driver->find_element('html','tag_name');
}
# If things get nasty, we could fall back to PhantomJS.webpage.plainText
# var page = require('webpage').create();
# page.open('http://somejsonpage.com', function () {
# var jsonSource = page.plainText;
sub decoded_content {
$_[0]->driver->get_page_source
};
=head2 C<< $mech->content( %options ) >>
print $mech->content;
print $mech->content( format => 'html' ); # default
lib/WWW/Mechanize/PhantomJS/ghostdriver/config.js view on Meta::CPAN
"port" : defaultConfig.port,
"hub" : defaultConfig.hub,
"proxy" : defaultConfig.proxy,
"version" : defaultConfig.version,
"logFile" : defaultConfig.logFile,
"logLevel" : defaultConfig.logLevel,
"logColor" : defaultConfig.logColor,
"remoteHost": defaultConfig.remoteHost
},
logOutputFile = null,
logger = require("./logger.js"),
_log = logger.create("Config");
function apply () {
// Normalise and Set Console Logging Level
config.logLevel = config.logLevel.toUpperCase();
if (!logger.console.LEVELS.hasOwnProperty(config.logLevel)) {
config.logLevel = defaultConfig.logLevel;
}
logger.console.setLevel(logger.console.LEVELS[config.logLevel]);
lib/WWW/Mechanize/PhantomJS/ghostdriver/hub_register.js view on Meta::CPAN
// Ghostdriver process will interact in unexpected and undesirable ways.
maxSession: 1,
register: true,
registerCycle: 5000,
role: "wd",
url: "http://" + ip + ":" + port,
remoteHost: returnHost
}
};
},
_log = require("./logger.js").create("HUB Register");
module.exports = {
register: function(ip, port, hub, proxy, version, remoteHost) {
var page;
try {
page = require('webpage').create();
port = +port; //< ensure it's of type "number"
if(!hub.match(/\/$/)) {
hub += '/';
}
/* Register with selenium grid server */
page.open(hub + 'grid/register', {
operation: 'post',
data: JSON.stringify(nodeconf(ip, port, hub, proxy, version, remoteHost)),
headers: {
lib/WWW/Mechanize/PhantomJS/ghostdriver/logger.js view on Meta::CPAN
exports.create = function (context) {
return new Logger(context);
};
/**
* Export: Add Log File.
*
* @param logFileName {String Name of the file were to output (append) the Logs.
*/
exports.addLogFile = function(logFileName) {
var fs = require("fs"),
f = fs.open(fs.absolute(logFileName), 'a');
// Append line to Log File
console.onOutput(function(msg, levelName) {
f.writeLine(msg);
f.flush();
});
// Flush the Log File when process exits
phantom.aboutToExit.connect(f.flush);
lib/WWW/Mechanize/PhantomJS/ghostdriver/main.js view on Meta::CPAN
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var server = require("webserver").create(), //< webserver
router, //< router request handler
_log; //< logger for "main.js"
// "ghostdriver" global namespace
ghostdriver = {
system : require("system"),
hub : require("./hub_register.js"),
logger : require("./logger.js"),
webdriver_logger : require("./webdriver_logger.js"),
config : null, //< this will be set below
version : "2.1.0"
};
// create logger
_log = ghostdriver.logger.create("GhostDriver");
// Initialize the configuration
require("./config.js").init(ghostdriver.system.args);
ghostdriver.config = require("./config.js").get();
// Enable "strict mode" for the 'parseURI' library
require("./third_party/parseuri.js").options.strictMode = true;
// Load all the core dependencies
// NOTE: We need to provide PhantomJS with the "require" module ASAP. This is a pretty s**t way to load dependencies
phantom.injectJs("session.js");
phantom.injectJs("inputs.js");
phantom.injectJs("request_handlers/request_handler.js");
phantom.injectJs("request_handlers/status_request_handler.js");
lib/WWW/Mechanize/PhantomJS/ghostdriver/request_handlers/request_handler.js view on Meta::CPAN
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var ghostdriver = ghostdriver || {};
ghostdriver.RequestHandler = function() {
// private:
var
_errors = require("./errors.js"),
_handle = function(request, response) {
// NOTE: Some language bindings result in a malformed "post" object.
// This might have to do with PhantomJS poor WebServer implementation.
// Here we override "request.post" with the "request.postRaw" that
// is usually left intact.
if (request.hasOwnProperty("postRaw")) {
request["post"] = request["postRaw"];
}
_decorateRequest(request);
lib/WWW/Mechanize/PhantomJS/ghostdriver/request_handlers/request_handler.js view on Meta::CPAN
_decorateRequest(request);
// Handle the re-routed request
this.handle(request, response);
},
_decorateRequest = function(request) {
// Normalize URL first
request.url = request.url.replace(/^\/wd\/hub/, '');
// Then parse it
request.urlParsed = require("./third_party/parseuri.js").parse(request.url);
},
_writeJSONDecorator = function(obj) {
this.write(JSON.stringify(obj));
},
_successDecorator = function(sessionId, value) {
this.statusCode = 200;
if (arguments.length > 0) {
// write something, only if there is something to write
lib/WWW/Mechanize/PhantomJS/ghostdriver/request_handlers/session_request_handler.js view on Meta::CPAN
},
_getUrlCommand = function(req, res) {
// Get the URL at which the Page currently is
var result = _protoParent.getSessionCurrWindow.call(this, _session, req).url;
res.respondBasedOnResult(_session, res, {status: 0, value: result});
},
_canonicalURL= function( url ) {
var URL= require("./third_party/parseuri.js");
//console.log(''+url + " => " + JSON.stringify(URL.parse(url)));
var canonicalURL= URL.parse(url);
if( !canonicalURL.path || 0==canonicalURL.path.length ) {
// Add the trailing slash
canonicalURL.path='/';
};
var s= canonicalURL.protocol + '://'
+ (canonicalURL.authority ? (canonicalURL.authority) : '')
+ (canonicalURL.path)
+ (canonicalURL.query ? '?' + canonicalURL.query : '')
lib/WWW/Mechanize/PhantomJS/ghostdriver/request_handlers/session_request_handler.js view on Meta::CPAN
// set default values
if (!postObj.cookie.path) {
postObj.cookie.path = "/";
}
if (!postObj.cookie.secure) {
postObj.cookie.secure = false;
}
if (!postObj.cookie.domain) {
postObj.cookie.domain = require("./third_party/parseuri.js").parse(currWindow.url).host;
}
if (postObj.cookie.hasOwnProperty('httpOnly')) {
postObj.cookie.httponly = postObj.cookie.httpOnly;
delete postObj.cookie['httpOnly'];
} else {
postObj.cookie.httponly = false;
}
// JavaScript deals with Timestamps in "milliseconds since epoch": normalize!
lib/WWW/Mechanize/PhantomJS/ghostdriver/request_handlers/webelement_request_handler.js view on Meta::CPAN
return resultStr;
},
_postValueCommand = function(req, res) {
var postObj = JSON.parse(req.post),
currWindow = _protoParent.getSessionCurrWindow.call(this, _session, req),
typeRes,
text,
isFileInputRes,
isContentEditableRes,
fsModule = require("fs"),
abortCallback = false,
multiFileText;
isFileInputRes = currWindow.evaluate(require("./webdriver_atoms.js").get("is_file_input"), _getJSON());
isFileInputRes = JSON.parse(isFileInputRes);
if (isFileInputRes && isFileInputRes.status !== 0) {
res.respondBasedOnResult(_session, req, isFileInputRes);
return;
}
lib/WWW/Mechanize/PhantomJS/ghostdriver/request_handlers/webelement_request_handler.js view on Meta::CPAN
_getNameCommand = function(req, res) {
var result = JSON.parse(_protoParent.getSessionCurrWindow.call(this, _session, req).evaluate(
require("./webdriver_atoms.js").get("get_name"),
_getJSON()));
res.respondBasedOnResult(_session, req, result);
},
_getAttributeCommand = function(req, res) {
var attributeValueAtom = require("./webdriver_atoms.js").get("get_attribute_value"),
result;
if (typeof(req.urlParsed.file) === "string" && req.urlParsed.file.length > 0) {
// Read the attribute
result = _protoParent.getSessionCurrWindow.call(this, _session, req).evaluate(
attributeValueAtom, // < Atom to read an attribute
_getJSON(), // < Element to read from
req.urlParsed.file); // < Attribute to read
res.respondBasedOnResult(_session, req, result);
lib/WWW/Mechanize/PhantomJS/ghostdriver/request_handlers/webelement_request_handler.js view on Meta::CPAN
cssPropertyName);
res.respondBasedOnResult(_session, req, result);
return;
}
throw _errors.createInvalidReqMissingCommandParameterEH(req);
},
_getAttribute = function(currWindow, attributeName) {
var attributeValueAtom = require("./webdriver_atoms.js").get("get_attribute_value"),
result = currWindow.evaluate(
attributeValueAtom, // < Atom to read an attribute
_getJSON(), // < Element to read from
attributeName); // < Attribute to read
return JSON.parse(result).value;
},
/**
lib/WWW/Mechanize/PhantomJS/ghostdriver/session.js view on Meta::CPAN
// "setTimeout/setInterval" accept only 32 bit integers, even though Number are all Doubles (go figure!)
// Interesting details here: {@link http://stackoverflow.com/a/4995054}.
_max32bitInt = Math.pow(2, 31) -1, //< Max 32bit Int
_timeouts = {
"script" : 30000,
"implicit" : 0,
"page load" : 300000,
},
_windows = {}, //< NOTE: windows are "webpage" in Phantom-dialect
_currentWindowHandle = null,
_cookieJar = require('cookiejar').create(),
_id = require("./third_party/uuid.js").v1(),
_inputs = ghostdriver.Inputs(),
_capsPageSettingsPref = "phantomjs.page.settings.",
_capsPageCustomHeadersPref = "phantomjs.page.customHeaders.",
_capsPageZoomFactor = "phantomjs.page.zoomFactor",
_capsPageBlacklistPref = "phantomjs.page.blacklist",
_capsPageWhitelistPref = "phantomjs.page.whitelist",
_capsUnhandledPromptBehavior = "unhandledPromptBehavior",
_capsLoggingPref = "loggingPrefs",
_capsBrowserLoggerPref = "OFF",
_capsHarLoggerPref = "OFF",
lib/WWW/Mechanize/PhantomJS/ghostdriver/session.js view on Meta::CPAN
},
_decorateNewWindow = function(page) {
var k;
// Decorating:
// 0. Pages lifetime will be managed by Driver, not the pages
page.ownsPages = false;
// 1. Random Window Handle
page.windowHandle = require("./third_party/uuid.js").v1();
// 2. Initialize the One-Shot Callbacks
page["onUrlChanged"] = _oneShotCallbackFactory(page, "onUrlChanged");
page["onFilePicker"] = _oneShotCallbackFactory(page, "onFilePicker");
page["onCallback"] = _oneShotCallbackFactory(page, "onCallback");
// 3. Utility methods
page.execFuncAndWaitForLoad = _execFuncAndWaitForLoadDecorator;
page.setOneShotCallback = _setOneShotCallbackDecorator;
page.waitIfLoading = _waitIfLoadingDecorator;
lib/WWW/Mechanize/PhantomJS/ghostdriver/session.js view on Meta::CPAN
return page;
},
_init = function() {
var page;
// Ensure a Current Window is available, if it's found to be `null`
if (_currentWindowHandle === null) {
// Create the first Window/Page
page = require("webpage").create();
// Decorate it with listeners and helpers
page = _decorateNewWindow(page);
// set session-specific CookieJar
page.cookieJar = _cookieJar;
// Make the new Window, the Current Window
_currentWindowHandle = page.windowHandle;
// Store by WindowHandle
_windows[_currentWindowHandle] = page;
}
},
lib/WWW/Mechanize/PhantomJS/ghostdriver/session.js view on Meta::CPAN
// Release CookieJar resources
_cookieJar.close();
},
_getLog = function (type) {
var har, i, entry, attrName,
page, tmp, tmpResMap;
// Return "HAR" as Log Type "har"
if (type === _const.LOG_TYPES.HAR) {
har = require('./third_party/har.js');
page = _getCurrentWindow();
tmpResMap = {};
for (i = 0; i < page.resources.log.length; i++) {
entry = page.resources.log[i];
if (!tmpResMap[entry.id]) {
tmpResMap[entry.id] = {
id: entry.id,
request: null,
startReply: null,
lib/WWW/Mechanize/PhantomJS/ghostdriver/third_party/uuid.js view on Meta::CPAN
for (var c = 0 ; c < 16; c++) {
_rndBytes[c] = _rnds[c >> 2] >>> ((c & 0x03) * 8) & 0xff;
}
return _rndBytes;
}
}
// Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
// Node.js only, moderately fast, high quality
try {
var _rb = require('crypto').randomBytes;
nodeRNG = _rb && function() {
return _rb(16);
};
} catch (e) {}
// Select RNG with best quality
var _rng = nodeRNG || whatwgRNG || mathRNG;
// Buffer class to use
var BufferClass = typeof(Buffer) == 'function' ? Buffer : Array;
lib/WWW/Mechanize/PhantomJS/ghostdriver/webdriver_atoms.js view on Meta::CPAN
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var fs = require("fs"),
atomsCache = {};
exports.get = function(atomName) {
var atomFileName = module.dirname + "/third_party/webdriver-atoms/" + atomName + ".js";
// Check if we have already loaded an cached this Atom
if (!atomsCache.hasOwnProperty(atomName)) {
try {
atomsCache[atomName] = fs.read(atomFileName);
} catch (e) {
lib/WWW/Mechanize/PhantomJS/ghostdriver/webelementlocator.js view on Meta::CPAN
"id", //< Returns an element whose ID attribute matches the search value.
"name", //< Returns an element whose NAME attribute matches the search value.
"link text", "linkText", //< Returns an anchor element whose visible text matches the search value.
"partial link text", "partialLinkText", //< Returns an anchor element whose visible text partially matches the search value.
"tag name", "tagName", //< Returns an element whose tag name matches the search value.
"xpath" //< Returns an element matching an XPath expression.
];
var
_session = session,
_errors = require("./errors.js"),
_log = ghostdriver.logger.create("WebElementLocator"),
_find = function(what, locator, rootElement) {
var currWindow = _session.getCurrentWindow(),
findRes,
findAtom = require("./webdriver_atoms.js").get(
"find_" +
(what.indexOf("element") >= 0 ? what : "element")), //< normalize
errorMsg;
if (currWindow !== null &&
locator && typeof(locator) === "object" &&
locator.using && locator.value && //< if well-formed input
_supportedStrategies.indexOf(locator.using) >= 0) { //< and if strategy is recognized
_log.debug("_find.locator", JSON.stringify(locator));