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

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

问题描述

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

我对类似的问题感兴趣:

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

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

有没有办法通过 Javascript 将当前页面下载为文件,或者复制到剪贴板是我唯一的选择?

编辑Stefan Kendall 和 dj_segfault 建议的一个选项是编写结果服务器端供以后检索.好主意,但不幸的是,在这种情况下,编写服务器端文件是不可能的.

如何 shudderinnerHTML 作为 post 参数传递给另一个页面?

解决方案

你可以试试协议data:text/attachment

喜欢:

<头><风格></风格><身体><div id="你好"><span>世界</span>

<脚本>(功能(){文档.位置 ='data:text/attachment;,' +//这里是技巧document.getElementById('hello').innerHTML;//document.documentElement.innerHTML;//下载整个Html源代码})();

编辑在shesek评论后

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天全站免登陆