【发布时间】:2020-07-28 14:43:40
【问题描述】:
我想要一个本地 .html 文件。当我在 safari 中打开它时,它会自动将某个 URL 下载为 html 文件。
我设法获得一个 .html 文件以将某个 URL 下载为 html 文件,使用以下代码,按照说明here。
<!DOCTYPE html>
<html>
<body>
<a href="https://stackoverflow.com/questions/11438864/get-html-content-from-another-site" download >a website</a>
<script src="./jquery.js"></script>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$("a[download]").click(function(e) {
e.preventDefault();
$.ajax({
url: "https://cors-anywhere.herokuapp.com/" + $(this).attr("href"),
headers: {
"X-Requested-With": "true"
},
success: function(data) {
console.log("The data is:", data);
var a = $('<a></a>');
a.attr("href", window.URL.createObjectURL(new Blob([data], {
type: 'text/plain'
})));
a.attr("download", "page.html");
$("body").append(a);
a[0].click();
}
});
});
</script>
</body>
</html>
我还设法获得一个 .html 文件以自动访问 URL,使用以下代码,按照说明 here。
<html>
<head>
<title>Start Auto Download file</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
$('a[data-auto-download]').each(function(){
var $this = $(this);
setTimeout(function() {
window.location = $this.attr('href');
}, 0000);
});
});
</script>
</head>
<body>
<div class="wrapper">
<p>The download should start shortly. If it doesn't, click
<a data-auto-download href="https://stackoverflow.com/questions/156686/how-to-start-automatic-download-of-a-file-in-internet-explorer">here</a>.
</p>
</div>
</body>
</html>
当我尝试合并两个代码时(见下文),我得到错误
undefined 不是一个对象(评估 'e.preventDefault')
.
<html>
<head>
<title>Start Auto Download URL as html file</title>
<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function() {
$('a[data-auto-download]').each(function(){
var $this = $(this);
setTimeout(function(e) {
e.preventDefault();
$.ajax({
url: "https://cors-anywhere.herokuapp.com/" + $(this).attr("href"),
headers: {
"X-Requested-With": "true"
},
success: function(data) {
console.log("The data is:", data);
var a = $('<a></a>');
a.attr("href", window.URL.createObjectURL(new Blob([data], {
type: 'text/plain'
})));
a.attr("download", "page.html");
$("body").append(a);
a[0].click();
}
});
}, 0000);
});
});
</script>
</head>
<body>
<div class="wrapper">
<p>The download should start shortly. If it doesn't, click
<a data-auto-download href="https://stackoverflow.com/questions/156686/how-to-start-automatic-download-of-a-file-in-internet-explorer">here</a>.
</p>
</div>
</body>
</html>
我太初级,无法调试它。请帮我。提前致谢。
【问题讨论】: