Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsdom not returning document

I am trying to use jsdom to load a local HTML file, this is the code

var config = {
      file: "filename",
      scripts: ["node_modules/jquery/dist/jquery.min.js"]
      done: function(err, window){
          console.log(window.document.URL)
          console.log(window.document.children)
      }
}
jsdom.env(config)

window.document.URL displays the correct url, but window.document.innerHTML doesnt have any data. Ive even tried

var config = {
      text: *raw-html*,
      scripts: ["node_modules/jquery/dist/jquery.min.js"]
      done: function(err, window){
          console.log(window.document.children)
      }
}

but I had the same results, any help?

Update

I have found that

var rawhtml = fs.readFileSync("filename.html","utf8")
jsdom.env(
  rawhtml,
  ["http://code.jquery.com/jquery.js"],
  function (err, window) {
    console.log(window.$("html").html())
  }
);

works as expected (it logs everything inside the html tags)

I then found that

config = {
  file: "filename.html",
  scripts: ["http://code.jquery.com/jquery.js"],
  done: function (err, window) {
    var $ = window.$;
    console.log($("html").html());
  }
} 
jsdom.env(config); 

also works, but again neither will create the document object correctly

"Solution"

jsdom does not show the output of document.children in the same way a browser console would, however, all of the functionality you would expect is there. The final working document object is below

var func = function(document){
  console.log(document.body.innerHTML)
  document.body.innerHTML = "i changed the body"


}
function getdoc(file, func){
  var document;
  jsdom.env(
    file,
    (err, window) => {
      document = window.document
      func(document)
      }
  );
}
getdoc("index.html",code)

I use jsdom.env() to get the document, then pass the document to func where all the fun javascript magic is free to happen. Keep in mind that any changes made to the document need to be manually saved.

like image 391
Shane Abram Mendez Avatar asked Nov 09 '22 13:11

Shane Abram Mendez


1 Answers

There is no document.innerHTML property.

Check "innerHTML" in document; -you'll get false.

like image 196
Bekim Bacaj Avatar answered Nov 14 '22 22:11

Bekim Bacaj