Created
January 31, 2013 16:19
-
-
Save asciidisco/4684043 to your computer and use it in GitHub Desktop.
Access PhantomJS via WebDriver/JSONWireProtocol from node to receive the title of a webpage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// before you launch this script, make sure you have phantomjs v1.8 installed | |
// and launch it with the port specified in the options: ´$ phantomjs --webdriver=3456´ | |
var http = require('http'); | |
// request body for "/wd/hub/session" request | |
var body = JSON.stringify({desiredCapabilities: {browserName: 'firefox', version: '', platform: 'ANY'}}); | |
// base options for post requests | |
var options = { | |
hostname: "localhost", | |
port: 3456, | |
path: "/wd/hub/session", | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
"Content-Length": body.length | |
} | |
}; | |
// create a new client request (get a fresh session) | |
var req = new http.ClientRequest(options); | |
// setup eventhandler that will be fired if we receive a response from the "/wd/hub/session" request | |
req.on('response', function (response) { | |
if (response.statusCode === 303 || response.statusCode === 200) | |
// distill the session id out of the response | |
var sessionid = response.headers.location.replace('http://' + options.hostname + ':' + options.port + options.path + '/', ''); | |
// prepare body & options for the "/url" goto post request (here, goes to denkwerk.com) | |
var body = JSON.stringify({url: 'http://denkwerk.com'}); | |
options.path = '/wd/hub/session/' + sessionid + '/url'; | |
options.headers['Content-Length'] = body.length; | |
var req2 = new http.ClientRequest(options); | |
// setup eventhandler that will be fired if we receive a response from the "/wd/hub/session/:sessionId/url" request | |
req2.on('response', function (response) { | |
if (response.statusCode === 200) { | |
// make a get request to the webrdriver and grab the title of the webpage (denkwerk.com) | |
http.get('http://' + options.hostname + ':' + options.port + '/wd/hub/session/' + sessionid + '/title', function(response) { | |
var incoming = ''; | |
if (response.statusCode == 200) { | |
response.on('data', function (chunk) { incoming += chunk; }); | |
response.on('end', function () { console.log('TITLE:', JSON.parse(incoming).value); }); | |
} | |
}); | |
} | |
}); | |
// fire "/wd/hub/session/:sessionId/url" request | |
req2.end(body); | |
}); | |
// "/wd/hub/session" request | |
req.end(body); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice