The objective is to be able to click a link to bring up a new window that displays the formatted source code from the parent window.
Through research, I was able to accomplish most of the task, but I need the new window to display the source code exactly as it is in the parent, indentation and all. Currently, HTML entities are being displayed as their display counterpart (so it outputs the actual trademark instead of the source's ™
).
I was thinking of looping through a bunch of entities and doing a string replace, as you'll see in my example, but I'm thinking that the logic is off, and I don't know what's going on.
Entities in particular: • (bull), & (amp), ® (reg), ™ (trade), < (lt), > (gt)
Here's the code the hyperlink launches that I have so far, bonus to anyone who can figure out what the closing body tag is being output on a second line (I'm stumped):
Thank you very much in advance for any direction leading to resolution.
function viewSource( e )
{
e.preventDefault( );
var source = '<!DOCTYPE html>' + "\n"
+ '<html xmlns="http://www.w3.org/1999/xhtml">' + "\n\n"
+ "\t" + document.getElementsByTagName( 'html' )[0].innerHTML + "\n\n"
+ '</html>';
entities = [
new Entity( '<', '<' ),
new Entity( '>', '>' )
];
for ( var i = 0; i < entities.length; i++ )
{
var regex = new RegExp( entities[i].entity, 'g' );
source = source.replace( regex, entities[i].html );
}
source = '<pre>' + source + '</pre>';
var sourceWindow = window.open( '', '_blank' );
sourceWindow.document.write( source );
sourceWindow.document.close( );
if ( window.focus )
{
sourceWindow.focus( );
}
}
Update (still unsolved mysteries):
I tried the suggestion to use an AJAX request, but it is still yield the same results (line 11 shows new Entity( '<', '<'),
). Here's what the AJAX attempt looks like:
function viewSource( e )
{
e.preventDefault( );
var xmlhttp;
if ( window.XMLHttpRequest )
{
// IE7+, Fx, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest( );
}
else
{
// IE6, IE5
xmlhttp = new ActiveXObject( 'Microsoft.XMLHTTP' );
}
xmlhttp.onreadystatechange =
function ( )
{
if ( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
{
var source = xmlhttp.responseText.replace( /</g, '<' ).replace( />/g, '>' );
source = '<pre>' + source + '</pre>';
var sourceWindow = window.open( '', '_blank' );
sourceWindow.document.write( source );
sourceWindow.document.close( );
if ( window.focus )
{
sourceWindow.focus( );
}
}
};
xmlhttp.open( 'GET', '/', true );
xmlhttp.send( );
}
new Entity( '<', '<' ),
. I suppose my proposed solution will not work. Perhaps, an alternative like just being able to execute the command "view-source:index.html" could work? I was having trouble getting that to work in IE9. – MrSlayer Nov 4 '11 at 2:51View Source
shows the original source from the server, not the current state of the DOM. If you want that, you can just use AJAX. – SLaks Nov 4 '11 at 3:00