为了解决这个问题,我们需要使用window对象的beforeunload事件,当页面将要被卸载时,触发这个事件,然后使用Content-Disposition = attachment头,将在页面上的内容作为附件下载而不是直接打开。以下是一个示例代码:
HTML代码:
这是将要被下载的内容。
JavaScript代码:
function download() { window.addEventListener('beforeunload', function(e) { e.preventDefault(); e.returnValue = ''; });
var data = document.querySelector('p').innerText;
var blob = new Blob([data], { type: 'text/plain' });
var url = URL.createObjectURL(blob);
var link = document.createElement('a');
link.href = url;
link.download = 'download.txt';
link.click();
window.removeEventListener('beforeunload');
setTimeout(function() {
URL.revokeObjectURL(url);
}, 1000);
}