在iOS 26.5.2版本的Safari中,使用HTML5/JavaScript生成并保存文件。
我有一个静态网站,使用JavaScript为用户生成一个文件以供保存。
我一直在参考 https://stackoverflow.com/a/18197511,在iOS Safari上运行良好。
然而,最近我发现升级到iOS 26.5.2之后,这个方案不再起作用。
用户仍然会看到“Do you want to download "a.txt" on ...?”,但在点击“下载”后,文件并不会出现在用户的下载文件夹(Files应用中)。
有没有其他方式下载JS生成的文件?或者这是一个iOS/Safari的 Bug?我的网站是静态的,因此无法从服务器提供该文件。
示例代码:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<button onclick="download('a.txt', 'foo\nbar\n');">Download</button>
<script type="text/javascript">
function download(filename, text) {
var pom = document.createElement('a');
pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
}
</script>
</body>
解决方案
我注意到(在Google的 AI的帮助下)使用Blob就能工作。新的URL看起来像 blob:https://example.com/8f6f5b99-1dd5-4301-a7ac-523a38b8d6ed。之前的URL看起来像 data:text/plain;charset=utf-8,foo%0Abar%0A。
完整的PoC:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<button onclick="download('a.txt', 'foo\nbar\n');">Download</button>
<script type="text/javascript">
function download(filename, text) {
const blob = new Blob([text], { type: 'text/plain' });
const href = URL.createObjectURL(blob);
var pom = document.createElement('a');
pom.setAttribute('href', href);
pom.setAttribute('download', filename);
if (document.createEvent) {
var event = document.createEvent('MouseEvents');
event.initEvent('click', true, true);
pom.dispatchEvent(event);
}
else {
pom.click();
}
URL.revokeObjectURL(href);
}
</script>
</body>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。