如何使用Javascript将文件/附件下载当前页面? [英] How to download the current page as a file / attachment using Javascript?

查看:122
本文介绍了如何使用Javascript将文件/附件下载当前页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这里提到的隐藏的iFrame技巧(http://stackoverflow.com/questions/365777/starting-file-download-with-javascript)和其他答案。



我对类似的问题感兴趣:



如何使用Javascript下载当前的页面(IE:当前的DOM或它的一些子集)作为一个文件?



我有一个网页,从非确定性查询(例如,随机样本)显示给用户。我可以通过querystring参数使页面返回一个文件,而不是渲染页面。我可以添加获取文件版本按钮(我们的标准方法),但结果将与显示的结果不同,因为它是不同的查询运行。



是有什么办法通过Javascript下载当前页面作为一个文件,还是复制到剪贴板我唯一的选项?



编辑
Stefan Kendall和dj_segfault建议的一个选项是将结果服务器端写入以后进行检索。好的想法,但不幸的是写文件服务器端是这个例子中的问题。



如何颤抖传递 innerHTML 作为另一个页面的post参数?

解决方案

您可以尝试使用协议 data:text / attachment



喜欢:

 < HTML> 
< head>
< style>
< / style>
< / head>
< body>
< div id =hello>
< span> world< / span>
< / div>
< script>
(function(){
document.location =
'data:text / attachment;'+ //这里是窍门
document.getElementById('hello')。 innerHTML;
//document.documentElement.innerHTML; //下载整个Html源
})();
< / script>
< / body>
< / html>

修改

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?

解决方案

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

这篇关于如何使用Javascript将文件/附件下载当前页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆