Skip to content

Instantly share code, notes, and snippets.

@stawecki
Created May 14, 2011 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save stawecki/972742 to your computer and use it in GitHub Desktop.
Save stawecki/972742 to your computer and use it in GitHub Desktop.
Sample WebKit Remote Control with JavaScript via Remote Debug script
<script>
var socket;
var seqNo = 1;
var seqCallback = [];
var remoteOnChange;
var remoteOnLoad;
var remoteURL;
function remoteEval(scriptString,callback) {
seqCallback[seqNo] = callback;
socket.send('{"seq":'+seqNo+',"domain":"Runtime","command":"evaluate","arguments":{"expression":"'+
scriptString.replace(/[\"]/g,'\\"')
+'","objectGroup":"console","includeCommandLineAPI":false}}');
seqNo++;
}
remoteOnChange = function(result) { remoteURL = result.url; };
function init() {
var host = "ws://localhost:9222/devtools/page/5"; // Set page number!
socket = new WebSocket(host);
socket.onopen = function(msg){ run(); };
socket.onmessage = function(msg){
console.log('onMessage: '+msg.data);
try
{
var responseObj = JSON.parse(msg.data);
if (responseObj.seq > 0) {
if (seqCallback[responseObj.seq] != undefined)
{
seqCallback[responseObj.seq](responseObj.body.result.description);
}
}
if (responseObj.event == "inspectedURLChanged" && remoteOnChange != undefined)
{
remoteOnChange(responseObj.body);
}
if (responseObj.event == "loadEventFired" && remoteOnLoad != undefined)
{
remoteOnLoad();
}
} catch(err) {}
}
}
function run(){
remoteOnLoad = function(result) {
// We might've ended up on the login page, so let's log in!
if (remoteURL.indexOf("ServiceLogin") > 0 )
remoteEval( " document.getElementById('Email').value = 'username'; "+
" document.getElementById('Passwd').value = 'password'; "+
" document.getElementsByTagName('form')[0].submit(); "
, function(result) { alert(result); } );
// We're home!
if (remoteURL.indexOf("mail.google.com/mail/") > 0 )
remoteEval( " try { document.getElementById('canvas_frame').contentWindow.document."+
"getElementsByClassName( 'md' )[0].innerText } catch(e) { -1 }"
, function(result) { // Waiting for AJAX:
if (result == -1) { setTimeout(remoteOnLoad,2000); } // Try again in 2 sec.
else { alert(result); } } ); // This should return scraped information
// about your data usage on gmail! :D
} ;
// This happenes first:
remoteEval(" location.href = 'http://gmail.com' "); //Let's go to Gmail!
} ;
</script>
<body onload="init()">
<textarea id="remoteText" cols="100" ></textarea><input type="button" value="Remote eval"
onclick=" remoteEval( document.getElementById('remoteText').value , function(result) { alert(result); } ); " />
</body>
@stawecki
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment