Save the document generated by javascript

OscarRyz picture OscarRyz · Sep 25, 2009 · Viewed 32k times · Source

Javascript can manipulate the document the browser is displaying, so the following:

<script>
    document.write("<table><tr><td>Hola</td><td>Adios</td></tr></table>");
</script>

Will make the browser display a table just like if it was the original HTML document:

<table>
    <tr>
        <td>Hola</td>
        <td>Adios</td>
    </tr>
</table>

Is there a way I can save/serve this document content?

Currently we have some nicely generated reports using Ext-js, what I would like to do is to have the "text/html" version of it ( I mean, something that doesn't require javascript )

So at the end of the page I would add a button : "Save as blaba" and the document should display the text/plain version.

The only way I could think right now is, to write the content into a javascript variable like:

 var content = document.toString(); // or something magic like that.
 // post it to the server

Then post that value to the server, and have the server present that value.

 <%=request.getParameter("content-text")%>

But looks very tricky.

Is there an alternative?

EDIT

Ok, I almost got it. Now I just need the new window to pop up so the option "would you like to save it shows"

This is what I've got so far

<script>
    document.write("<div id='content'><table><tr><td>Hola</td><td>Adios</td></tr></table></div>");
    function saveAs(){
        var sMarkup =  document.getElementById('content').innerHTML; 
        var oNewDoc = document.open('application/vnd.ms-excel');        
        oNewDoc.write( sMarkup + "<hr>" );
        oNewDoc.close();
    }
</script>

<input type="button" value="Save as" onClick="saveAs()"/>

The line:

    var oNewDoc = document.open('application/vnd.ms-excel');        

Should specify the new content type, but it is being ignored.

Answer

Esteban K&#252;ber picture Esteban Küber · Sep 25, 2009

Unless its being saved client side with File -> Save Page As..., you will have to do exactly what you are proposing, posting $('body').html() to your server and process it as text.