Save html page with js

How do i save a webpage with javascript

Ok so im making a test and i am trying to save the way the page looks after a user has taken the test so that way they can access it on a server side table to review its answers. I have looked and have not really found a way to do this. The idea is after the user has submitted the test it will show right and wrong answers, save, then that page is sent to the table. Any help is appreciated. In case anyone is curious here is my code :

function finishTest()< //There are actually 37 questions on the test so far only included 3 var score = 0; var totalQuestions = 37; for(var questionNum = 1; questionNumelse if (radios[i].checked && radios[i].value=="0") < alert(radios.innerHTML); radios[i].parentNode.style.backgroundColor = "orangered"; >> > score = parseFloat(score*100/totalQuestions).toFixed(1); alert("You scored "+score+"%"); document.getElementById('finish').style.visibility='hidden'; > 

2 Answers 2

As lwalden answered, it is generally the right idea to save save the user’s input and repopulate the document with those values later, rather than saving and restoring the entire document. That’s a basic part of working with forms and user input.

Just for some fun and to directly answer your question, here is a basic example. Again, this is not the proper way to approach your project.

    

Saved doc:

var saveBtn = document.getElementById('save-btn'); saveBtn.addEventListener('click', function() < // get value of inputs and add them to the actual elements [].forEach.call(document.querySelectorAll('input'), function(input) < input.setAttribute('value', input.value); >); // get the document as a string var doc = document.documentElement.innerHTML; save(doc); >); // save it however you want, probably ajax request to a server // in this example, I'm saving it to localStorage function save(doc) < localStorage.doc = doc; loadSavedDoc(); >// loading the saved doc into an iframe function loadSavedDoc() < var savedDoc = document.getElementById('saved-doc'); savedDoc.contentWindow.document.documentElement.innerHTML = localStorage.doc; >loadSavedDoc(); 

Replying to your comment, this sample code is to help you get the idea of saving and restoring user input. In a real project, you’d probably want named input fields in forms, to save to an object, and a library/framework to keep the code minimal and clean.

var saveBtn = document.getElementById('save-btn'); var loadBtn = document.getElementById('load-btn'); var textInputs = document.querySelectorAll('input[type="text"]'); saveBtn.addEventListener('click', function() < var vals = []; [].forEach.call(textInputs, function(input) < vals.push(input.value); >); localStorage.vals = JSON.stringify(vals); >); loadBtn.addEventListener('click', function() < JSON.parse(localStorage.vals).forEach(function(val, idx) < textInputs[idx].value = val; >); >); 

Источник

Читайте также:  Php custom fatal error

How to save/update a HTML page locally using javascript?

So, I want to code a simple HTML page as an overlay for OBS and inside the page there is an input field which is editing content to an HTML element. I want to be able to save or update the entire page without right click Save As. Upon refreshing the page the edited content from the input field does not «stick». Is it possible to add a piece of javascript and a button to save/update the entire HTML page with edited content? This is the code I am using right now
Input field shows the typed text. Upon refreshing the page, typed content is gone. I need to update the page so the typed content is still visible upon refreshing the HTML document. I’m not a programmer, nor do I have extensive skills so please do not reply to my question with other questions using technical terms. And please DO not post a links to other so called solutions because I’ve already tested 22 «solutions» and nothing worked. Thank you.

 document.getElementById("ChangeIt").addEventListener("keyup", myFunction); function myFunction()

1 Answer 1

If your environment supports localStorage , then it should be pretty easy: any time an input changes, alter a localStorage value. Also, on pageload, go through localStorage and populate each input . For example:

const savedText = JSON.parse(localStorage.getItem('savedText')) || <>; Object.entries(savedText).forEach(([id, val]) => < document.getElementById(id).value = val; >); document.body.addEventListener('keyup', ( < target: < value, id >>) => < if (!id || !value) return; savedText[id] = value; localStorage.savedText = JSON.stringify(savedText); >) document.getElementById("ChangeIt").addEventListener("keyup", myFunction); function myFunction() < var elementValue = document.getElementById("ChangeIt").value; document.getElementById("username").innerHTML = elementValue; >myFunction(); 

I can’t embed it as a stack snippet because stack snippets don’t support localStorage .

Читайте также:  Сколько зарабатывает фрилансер python

Note that this implementation requires that each element that gets its value saved have an id , but of course you can tweak that to suit your needs.

Источник

how can i save the current HTML page locally via a button on page?

I have a very big HTML page with many large tables. I have tried to export the tables to excel and succeeded. But when dealing with 200K+ rows in a table, the browser crashes (Chrome and IE). So, I have decided to save the entire page locally. Can it be done? Thanks

what exactly do you want to save? just the raw HTML code? or the whole page including images, css, js?

4 Answers 4

If you need a download button that anyone can use on your site to save a file, use the download attribute.

This would work if its a static page. But not supported in old browsers including Edge 12, IE, Safari or Opera 12

I suppose that the data that is in these tables is loaded from your server somewhere. Wouldn’t it be better to create a downloadlink to an action on your server that creates these files instead of creating the files based on your html page?

One solution is to load the page in your browser and then go to File > Save As. This will open a dialoge that allows you to save the page as an html type file.

However if the webpage is so large that the browser cannot load it, use a tool like wget on linux to pull the entire page down without using a browser. After installing wget on a linux distribution, use it like so

Читайте также:  Зачем папка public html

This command will download the file to the current directory with name file.html

If you also want to download any included files in file.html (ie css or js files). Include the flags -p and -k .

Источник

Save the document generated by javascript

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 

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

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

11 Answers 11

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.

File-Save page as: would save «document.write(‘html. etc etc ) isn’t? I would like something like «File-Save as» and the saved that would be «

@Oscar Reyes: You could make a button that would open a new window with only the table with javascript, and save that.

@Oscar Reyes: you will have to do it serverside nevertheless. You have to get the full client table, post it to the server and open the new «page» in a new window. I’ll try to be more explicative later.

Here’s the upgraded version to open the table contents in .xls format.

      

This code is tested in IE6 and is using ActiveXObject control.

  • The table I’ve used here is of order 2×2 and the individual contents are mapped respectively into the excel sheet.
  • Unlike the .doc version, this does not save the file in client’s system. It opens the application with the table content and the client has to save it.

Hope this helps in answering ur question. Lemme know if u face any issues.

This looks very promising. I’ve tried in ie7 and I’m getting the following error. I’ll try it with ie6 ( my target ) in a while and ledt you know the result: img11.imageshack.us/img11/8444/capturatx.png The error message reads: The atomization server could not create the object

This code works fine if it is run locally[without the server environment]. To make it work in ‘server’ environment, you need to change some security settings to allow the creation of ActiveXObject in ur server system. Hit Tools>Internet Options>Security Tab>Custom Level> make sure «prompt» is selected for «Download signed and unsigned activeX controls».Then u’ll get a prompt when the code is run. If that didn’t help, try changing other related activeX options. But make sure u have an updated antivirus program b4 changing the security settings, if in case something goes wierd. :p

doh! I guess if I don’t the js-object will become undefined. I can handle that and say something like «You need MS-Office installed to save it as excel» etcetc . grrrreat. Thank you chong

Depending on your browser support requirements, you could use data URIs

Core for proof of concept (tested in Firefox 3.5.3):

I pulled base 64 encode/decode from examples online. Careful: the one I grabbed included a URI encode before base 64 encode that messed me up for a while.

You are getting close to the answer I thinks. The problem is that ‘ document.open(. ) ‘ can only take standard mime-types such as ‘text/html’, ‘text/plain’ and a few others

And because of that your code should be:

  
.table .table thead th .table tr td .table tr:hover td

If it’s just a report, you could use server-side JavaScript to generate it, and then serve it up with whatever MIME type you need.

It is actually. Can you point me in the right direction towards server-side javascript please? I have no idea.

I’ve never used it, but SpiderMonkey ( mozilla.org/js/spidermonkey ) will let you run JS from the command-line ( blog.ianbicking.org/jslint-command-line.html ). I guess you could then set up SpiderMonkey as a handler for your server-side scripts. There’s also Jaxer if you want a more end-to-end package.

I dont think that sending your html to the server is a tricky solution. You just have to remember to give a link to your user to download this file. This can be done using a traditional POST, or even using AJAX. It depends on how you want your users to interact if your page.

Using traditional post, you could put all the html content in the value attribute of an input type hidden in your page, named «html_content» or something like that, and when the user clicks in the button «save» you send your user to another page with a link do the file. You send the html to server, a script creates a file in a filesystem with an unique name, and returns a download link.

Using AJAX, you just need to do an AJAX POST passing this variable, and then your script returns a download link, and you dynamically put it in your html — without reloading your page, like it was «only cliente side».

Either way, you’ll return a link to the resource you just created in your filesystem with a html extension. Remember to generate unique names in your server for each generated file to avoid collisions.

Beware though that using innerHTML in IE 6 (I dont know if this is a IE family behavior or just about the 6 version) uppercases all tags and removes quotes from attributes. If you’re planning to do some post processing in your html, be careful.

I dont know how jQuery or other JS libraries behaves in such situations. I would suggest using it though, they have plenty of browser compatibility checks to abstract all these hacks we use.

Источник

Оцените статью