Search code examples
javascriptjqueryhtmliframeace-editor

Unwanted space in iframe source code output in Ace Editor


In my project, I am using Ace Editor and an iframe. The Ace Editor contains source code from the iframe.

The source code loads in the Ace Editor when the webpage loads. I am using this code to load the source code from the iframe to the Ace Editor:

function getCode()
{
var code = "<!DOCTYPE html>" + "\n" + document.getElementById("iframe_id").contentWindow.document.documentElement.outerHTML;
editor.getSession().setValue(code);
}

I have to output "<!DOCTYPE html>" manually because

document.getElementById("iframe_id").contentWindow.document.documentElement.outerHTML 

does not output the doctype.

When the webpage loads the Ace Editor loads the iframe source code:

<body onLoad="getCode()">

But the source code of the iframe in the Ace Editor looks like this:

<!DOCTYPE html>
<html><head>
<title>Learning HTML</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is your first webpage.</p>



</body></html>

But I want the code to be properly arranged like this:

<!DOCTYPE html>
<html>
<head>
<title>Learning HTML</title>
</head>
<body>
<h1>Welcome</h1>
<p>This is your first webpage.</p>
</body>
</html>

I do not know where the problem is. Please help.

UPDATE: - When I right click and see the source of the iframe the code is same as shown in the Ace editor.


Solution

  • You'll have to throw your code through an HTML beautifier (like js-beautify) before showing it in Ace if you want to achieve this. Ace doesn't have an option for this itself.

    See also this question.