Skip to content

Instantly share code, notes, and snippets.

@pyokagan
Created October 22, 2012 11:10
Show Gist options
  • Select an option

  • Save pyokagan/3931037 to your computer and use it in GitHub Desktop.

Select an option

Save pyokagan/3931037 to your computer and use it in GitHub Desktop.
Prints HTML contents of inspected node in Firebug. Requires firebug and mozrepl to be installed in Firefox. For Python 2.6, requires python-argparse.
#! /usr/bin/python2.6
#NOTE: Also python3 compatible.
from __future__ import print_function,unicode_literals
import time, json, sys, re
from argparse import ArgumentParser
from telnetlib import Telnet
class Mozrepl:
def __init__(self, host="127.0.0.1", port=4242):
self.host = host
self.port = port
def __enter__(self):
#Start Telnet
self.t = Telnet(self.host, self.port)
#Wait for Prompt, and detect repl name at the same time
_, match, _ = self.t.expect([br'(repl\d*)> '], timeout = 250)
if match is None:
raise Exception('Timeout: Could not detect prompt')
self._context = match.group(1)
self.context = match.group(1).decode()
self.prompt = match.group(0)
return self
def __exit__(self, type, value, traceback):
self.t.close()
del self.t
def js(self, command):
cmd = "(function(repl){{ eval({0}); }})({1});".format(json.dumps(command), self.context)
self.t.write(cmd.encode() + b"\n")
x = self.t.read_until(self.prompt).decode('utf-8', 'replace')
return x[:-(len(self.prompt))]
def main():
p = ArgumentParser()
p.add_argument("host", nargs="?", default = "localhost")
p.add_argument("port", nargs="?", default = 4242)
args = p.parse_args()
with Mozrepl(args.host, args.port) as x:
init_results = x.js(r"""repl.json_stringify = function(s) {
var jsonRegex = new RegExp('[\\u007f-\\uffff]', 'g');
var jsonRegexReplace = function(c) {
return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
};
var json = JSON.stringify(s);
return json.replace(jsonRegex, jsonRegexReplace);
}
repl.firebuglistener = {
onStartInspecting: function(context) {},
onInspectNode: function(context, node) {},
onStopInspecting: function(context, node, canceled) {
if (!canceled) {
repl.firebuginspectnode = node;
}
}
}
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator);
var i = 0;
for(var e = wm.getEnumerator("navigator:browser"); e.hasMoreElements();) {
i++;
e.getNext();
}
if (i > 1) {
repl.print("win warn");
}
repl.firebugwin = wm.getMostRecentWindow("navigator:browser");
if (repl.firebugwin) {
repl.print("win ok");
if (repl.firebugwin.Firebug) {
repl.print("firebug ok");
if (repl.firebugwin.Firebug.Inspector) {
repl.print("inspector ok");
repl.firebugwin.Firebug.Inspector.addListener(repl.firebuglistener);
}
}
}
""")
#Check init results
if init_results.find("win ok") == -1:
#Could not find browser window
print("error: No web browser window found!", file = sys.stderr)
sys.exit(1)
if init_results.find("win warn") != -1:
win_name = json.loads(x.js("repl.print(repl.json_stringify(repl.firebugwin.document.title))"))
print("warning: Multiple browser windows found. Using: {0}".format(win_name), file = sys.stderr)
if init_results.find("firebug ok") == -1:
print("error: Firebug not installed in firefox!", file = sys.stderr)
sys.exit(1)
if init_results.find("inspector ok") == -1:
print("error: Firebug has not been initialised in firefox. Initialise it by clicking the firebug icon.", file = sys.stderr)
sys.exit(1)
while True:
html = x.js(r'''
if (repl.firebuginspectnode) {
repl.print(repl.json_stringify(repl.firebuginspectnode.outerHTML));
}''')
if html.strip():
print(json.loads(html))
break
time.sleep(1)
x.js(r"repl.firebugwin.Firebug.Inspector.removeListener(repl.firebuglistener)")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment