Amit Gautam
Amit Gautam

Reputation: 71

How can I preserve the closing img tag while generating the HTML using Phantomjs?

I have simple use case as producing an HTML page using phantomjs. For simplicity I have created a plain HTML page. I use a javascript to open this HTML page and return the page contents as is. I execute this javascript through phantomjs command line. The problem is that my img tag in HTML has a closing tag. But the resulted HTML do not have this closing tag. This leaves my HTML as an invalid XML. I want a valid XML (or XHTML) at the end. But i guess phantomjs is applying some intelligence and removing my close img tag.

This is my HTML page "imagchart.html"

<html xmlns="http://www.w3.org/1999/xhtml">
  <body>
    <h2 class="header">Spectacular Mountain</h2>
    <img id="myImage" src="C:\Downloads\chart.png" />
  </body>
</html>

This is my test.js which opens the HTML page and produces the outer html.

var page = require('webpage').create();
page.open('file:///C:/Downloads/imagechart.html',function(status){
  if(status !== 'success'){
    console.log('Open failed');
  }else{		
    console.log(page.evaluate(function(){
        return document.documentElement.outerHTML;
   }));
} 
phantom.exit();
});

page.onResourceRequested = function (request) {
    //console.log('Request ' + JSON.stringify(request, undefined, 4));
};
I am running the phantomjs on command line as follows:

phantomjs test.js

This is the output from the phantomjs engine. Notice the closing tag from img is missing:

<html xmlns="http://www.w3.org/1999/xhtml">
  <body>
    <h2 class="header">Spectacular Mountain</h2>
    <img id="myImage" src="C:\Downloads\chart.png">
  </body>
</html>
My question is, how can i prevent the removal of closing img tag? I want a valid XHTML at the end.

Note: I tried changing the DOCTYPE in my HTML but it did not help.

Upvotes: 1

Views: 93

Answers (1)

Amit Gautam
Amit Gautam

Reputation: 71

Thanks guys, I got it working by just changing the file extension from imagchart.html to imagchart.xhtml This did the trick and now I get the closing tag for my IMG element.

Thanks.

Upvotes: 1

Related Questions