根据 @jcesarmobile 的建议,我得出了以下结论:
首先我必须安装cordova-插件-文件传输 https://github.com/apache/cordova-plugin-file-transfer
Open URL
var url = "http://mi-fancy-url.com";
var windowref = window.open(url, '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
创建一个监听器windowref
for a loadstart
事件并检查正在加载的内容是否是 pdf(这是我的情况)。
windowref.addEventListener('loadstart', function(e) {
var url = e.url;
var extension = url.substr(url.length - 4);
if (extension == '.pdf') {
var targetPath = cordova.file.documentsDirectory + "receipt.pdf";
var options = {};
var args = {
url: url,
targetPath: targetPath,
options: options
};
windowref.close(); // close window or you get exception
document.addEventListener('deviceready', function () {
setTimeout(function() {
downloadReceipt(args); // call the function which will download the file 1s after the window is closed, just in case..
}, 1000);
});
}
});
创建处理文件下载的函数,然后打开它:
function downloadReceipt(args) {
var fileTransfer = new FileTransfer();
var uri = encodeURI(args.url);
fileTransfer.download(
uri, // file's uri
args.targetPath, // where will be saved
function(entry) {
console.log("download complete: " + entry.toURL());
window.open(entry.toURL(), '_blank', 'location=no,closebuttoncaption=Cerrar,toolbar=yes,enableViewportScale=yes');
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
},
true,
args.options
);
}
我现在面临的问题是它的下载路径,我只是无法打开它。但还好,至少文件现在已经下载了。我必须创建一个 localStorage 项来保存不同文件的路径。
此步骤中缺少许多验证,这只是我快速制作的一个示例,用于检查它是否有效。需要进一步验证。