Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

How to download the current page as a file / attachment using Javascript?

I am aware of the hidden iFrame trick as mentioned here (http://stackoverflow.com/questions/365777/starting-file-download-with-javascript) and in other answers.

I am interested in a similar problem:

How can I use Javascript to download the current page (IE: the current DOM, or some sub-set of it) as a file?

I have a web page which fetches results from a non-deterministic query (eg. a random sample) to display to the user. I can already, via a querystring parameter, make the page return a file instead of rendering the page. I can add a "Get file version" button (our standard approach) but the results will be different to those displayed because it is a different run of the query.

Is there any way via Javascript to download the current page as a file, or is copying to the clipboard my only option?

EDIT An option suggested by Stefan Kendall and dj_segfault is to write the result server side for later retrieval. Good idea, but unfortunately writing files server side is out of the question in this instance.

How about shudder passing the innerHTML as a post parameter to another page?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can try with the protocol data:text/attachment

Like in:

<html>
<head>
    <style>
    </style>
</head>
<body>
    <div id="hello">
        <span>world</span>
    </div>
<script>
(function(){
    document.location = 
        'data:text/attachment;,' + //here is the trick
        document.getElementById('hello').innerHTML;
            //document.documentElement.innerHTML; //To Download Entire Html Source
})();
</script>
</body>
</html>

Edit after shesek comment


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...