Reputation: 43427
The bookmarklet I use grabs the current page's src in this way:
...
pre.appendChild(doc.createTextNode(document.documentElement.innerHTML));
...
What happens is that this dumps out whatever the browser yields as a string when looking up document.documentElement.innerHTML
.
This is not the same as the actual original source since the page could have been modified by javascript, for example.
Is it possible to have the bookmarklet retrieve the page again using an XHR or some such?
My goal is to have a bookmarklet that will GET a fresh copy of the page into a js string, which I can send to beautify.js
to clean it up (it provides great tools to clean up HTML, CSS and JS), then I fill up a <pre>
with the resulting beautified source string, which I will then use prettify.js
on. Since it'll be possible to link directly to these respective projects' js
files from my bookmarklet, this will be basically the king of all view-source bookmarks.
To date, I have been using the very excellent tools built into browsers like Google Chrome and Opera, but since I got the new iPad I really enjoy reading code on it so I'm attempting to move my workflow there.
Upvotes: 4
Views: 2281
Reputation: 42612
Here is an example using XHR:
var factories=[
function(){return new ActiveXObject("Microsoft.XMLHTTP")}, // for old IE
function(){return new XMLHttpRequest()}
];
function XHRMaker(){
var xhr=false,
i=factories.length;
while (0<=--i) {
try {
xhr=factories[i]();
break;
}catch (e){}
}
return xhr;
}
function getSource(cb){
var xhr=XHRMaker();
if (false===xhr) return false;
xhr.open('GET',window.location.href,true);
xhr.onreadystatechange=function(){
if (4!==xhr.readyState) return;
delete xhr.onreadystatechange;
cb(xhr.responseText);
};
xhr.send(null);
}
getSource(function(html){
alert(html);
});
using closure compiler, it compiles down to:
var c=[function(){return new ActiveXObject("Microsoft.XMLHTTP")},function(){return new XMLHttpRequest}];function d(){for(var b=!1,a=c.length;0<=--a;)try{b=c[a]();break}catch(e){}return b}(function(b){var a=d();if(!1===a)return!1;a.open("GET",window.location.href,!0);a.onreadystatechange=function(){4===a.readyState&&(delete a.onreadystatechange,b(a.responseText))};a.send(null)})(function(b){alert(b)});
or as bookmarklet code:
javascript:(function(){var%20c=[function(){return%20new%20ActiveXObject("Microsoft.XMLHTTP")},function(){return%20new%20XMLHttpRequest}];function%20d(){for(var%20b=!1,a=c.length;0<=--a;)try{b=c[a]();break}catch(e){}return%20b}(function(b){var%20a=d();if(!1===a)return!1;a.open("GET",window.location.href,!0);a.onreadystatechange=function(){4===a.readyState&&(delete%20a.onreadystatechange,b(a.responseText))};a.send(null)})(function(b){alert(b)});}());void(0);
Upvotes: 1