How to recover HTML bi Firefox source code via Addon/add-on?

I am writing an addon for Firefox. I need to get the source code of the HTML open in the current Firefox tab and display in a alert, using JavaScript.

I tried using alert(document.documentElement.outerHTML), but it just shows the code below:

insert the description of the image here

Any suggestions ?

Author: utluiz, 2014-06-04

2 answers

Since 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 a native-looking HTML with a lot more components). Well, when you click on the extension button, the current document is the Firefox window itself, soon it will display the XUL source code of the window.

I assume your JavaScript code is something like the below:

var seesource = {
  run : function(aEvent) {
    alert(document.documentElement.outerHTML);
  }
};

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

var seesource = {
  run : function(aEvent) {
    alert(content.document.documentElement.outerHTML);
  }
};

See result

alert () showing the HTML source code of pudim.com.br

This, however, does not apply if you are using the addon SDK, the most modern way to develop add-ons. In this case, the thing will be a little more complicated (in English) but clearly not your case.

 4
Author: brandizzi, 2017-05-23 12:37:26

If the page has jQuery included, the following works:

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

But to work on all pages, the ideal is to use the pure Javascript version:

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

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

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

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

request.send();

Can copy and paste to the console on any page for testing.

Tip: when you're unsure how to do something without jQuery, see: You Might Not Need jQuery

 1
Author: , 2014-06-04 11:25:59