Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save the document generated by javascript

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.

like image 264
OscarRyz Avatar asked Sep 25 '09 18:09

OscarRyz


People also ask

What does save () do in JavaScript?

save() method of the Canvas 2D API saves the entire state of the canvas by pushing the current state onto a stack.

What is the extension to save JavaScript File?

JavaScript files have the file extension .js.


1 Answers

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.

like image 167
Esteban Küber Avatar answered Oct 08 '22 14:10

Esteban Küber