这里有很多不必要的代码。
你已经宣布
downloadFile
作为一种功能。你不能只是加上
isChrome
和
isSafari
属性,并使用您使用的语法。你必须在十分钟内申报
downLoadFile
作为财产(带有
this.isSafari = ...
和
this.isChrome = ...
).但是,实际上你不需要属性,只需要变量。
而且,你实际上并没有打电话
下载文件
来自任何地方。
接下来,在窗口对象上创建新属性并依赖
navigator.userAgent
是反模式的。这正是我们不想做的。
你也不需要检查
link.download
.就这么定了。如果浏览器支持它,它将使用它。如果不支持,则不会抛出错误。
而且,你只需要使用
link.click()
而不是创建和发送事件。
有关更多信息,请参阅内联评论:
// If you are going to add properties to window, at least set them up in a
// namespace that you are 100% sure doesn't already exist.
window.CustomNamespace = {};
window.CustomNamespace.downloadFile = function (sUrl) {
// Create new link node.
var link = document.createElement('a');
link.href = sUrl;
// Browser detection is a futile effort because navigator.userAgent will often
// return inaccurate information and can be spoofed easily, creating security
// holes in your application. Additionally, testing for all the different clients
// and platforms is a never ending task. Use feature detection.
// All you really care about is whether the client supports the feature.
// You don't need to know what kind of client it is.
if (link.download) {
// download is supported. Just use it. Do you really care what browser it is?
link.download = random() + ".png";
console.log(link.download);
link.click(); // Trigger the click event - no need to create/dispatch a new event.
} else {
alert('Your device do not support files downloading. Please try again in desktop browser.');
}
}
function random() {
var length = 32,
charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
// Invoke the function
window.CustomNamespace.downloadFile("test");