How to recover source code HTML bi Firefox via Addon / Complement?

Posted on

Question :

I’m writing an addon to Firefox. I need to get the HTML source code open in the current Firefox tab and display in alert using JavaScript.

I tried to use alert(document.documentElement.outerHTML) , but just show the code below:

Any suggestions?


Answer :

As you are writing an add-on for Firefox, you should know that Firefox itself is a great program written in JavaScript and XUL (its weird markup language, which serves, in a way, as face-oriented HTML native and with many more components). Well, when you click the extension button, the current document is the Firefox window itself, so it will display the XUL source code of the window.

I assume your JavaScript code looks something like this:

var seesource = {
  run : function(aEvent) {

Fortunately, the scope of the scripts will contain a variable called content , which will reference the contents of the current tab. The key is to get the document of this variable:

var seesource = {
  run : function(aEvent) {

See the result

This,however,doesnotapplyifyouareusingthe Addon SDK , the modern way of developing add-ons. In this case, the thing will be a little more complicated but it is clearly not your case.

If the page has jQuery included, the following works:

$.get(document.html, function(html) { alert(html); } );

But to work on every page, it’s best to use the pure Javascript version:

// No IE, só funciona a partir da versão 9

request = new XMLHttpRequest();"GET", document.url, true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400){
    // Sucesso!
    html = request.responseText;
  } else {
    alert("O servidor retornou um erro")

request.onerror = function() {
  alert("Não foi possível conectar ao servidor");


You can copy and paste to the console on any page to test.

Tip: When in doubt about how to do something without jQuery, see: You Might Not Need jQuery p>

Leave a Reply

Your email address will not be published. Required fields are marked *