Serialize HTMLDocument and then render it on server?

After some Google search, I did not find anything that could fill my need. I want to save the current web page as well as what it is. I mean, on many web pages, Javascript is done and the CSS is changed, so after some interactive user, the web page may be different from the one that first loads into the browser. And I want to save the current state of the webpage on the server and render it on the server. Is there a Javascript library for this task? Thanks!

+6
javascript html
source share
4 answers

Serializing a full web page is as simple as:

var serialized = document.body.innerHTML; 

If you really need a complete document, including a head, then:

 var serialized = '<head>' + document.getElementsByTagName('head')[0].innerHTML + '</head><body>' + document.body.innerHTML + '</body>'; 

Now all you have to do is send it through AJAX.

On server side rendering, it depends on what you mean by visualization. I am currently using wkhtmltopdf to implement the "save as PDF" function on my site. It uses webKit to render HTML before creating PDF, so it fully supports CSS and javascript.

And if you need to save it in the image instead of a PDF file, you can always use ghostscript to print a PDF file to a JPG / PNG file.

+2
source share

Even simpler:

 var serialized = document.documentElement.innerHTML 

outerHTML instead of innerHTML would be better, but it does not work in Firefox.

Test it out.

  >>> document.body.style.color = 'red';
 >>> document.documentElement.innerHTML
 ...
 <body style = "color: red;">
 ... 
+2
source share

I am working on something similar and would like to share a summary of what I notice using innerHTML in IE8, FF3.6 and CHROME 5.0

IE

  • Clears quotes from many element attributes
  • Singleton nodes are not self-closed
  • If element values โ€‹โ€‹change after loading HTML, it raises new values

FF, CHROME

  • Singleton nodes are not self-closed
  • If the values โ€‹โ€‹of the elements change after the HTML has been loaded, it does NOT pick up the new values. It only picks up the default values โ€‹โ€‹set in the HTML during initial rendering.
+1
source share

this post mentions the serialiseWithStyles () function, the function calculates the styles for each element and prints the inline styles. this eliminates the need for separate style sheets.

then send it to the server, send a request for sending. use ajax or regular form.

0
source share

All Articles