I have a Div on my site, I want to place a button/link (or other things of the sort) that when clicked will save the div and all its contents to the users computer, much like the printing code which is used to print divs. I'm a coding novice so all help will be apreciated.
相关问题
- Views base64 encoded blob in HTML with PHP
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
There is a browser support limit doing this. HTML2Canvas can render your HTML content into a
canvas
element. Then you can usecanvas.toDataURL("image/png");
(docs in MDN) method to export thecanvas
element to anjpeg
orpng
image.It's not widely supported but it's still possible.
Easy way
use a button and call ur hidden field value
An easy way to do this would be to use GrabzIt's JavaScript API to capture a div. You would just need to do something like the following. Where #features is the id of the div you want to capture.
Disclaimer I built this API!
Assuming you want a text or HTML file, not an image file like a screen shot, JavaScript by itself can't initiate a "Save" dialog on a web browser, only a response from a web request to a server will do so.
To start with, you'll need a form with your button and a hidden field:
And you need some Javascript to save the DIV contents to the hidden field before submittal:
On the server, you'll need some code to accept the text and spit it back out in the form of a file attachment:
Caveat #1: There are probably some minor bugs in there and plenty of room for improvement, this is just a proof of concept.
Caveat #2: The server-side code above is potentially insecure, as it allows any web page to control content going to the user's web browser from your domain. You'll need to add some measures to protect this from being abused.