У вас здесь много ненужного кода.
Вы объявили downloadFile
как функцию.Затем вы не можете просто добавить свойства isChrome
и isSafari
к нему с использованием синтаксиса, который вы используете.Вам необходимо объявить их в downLoadFile
как свойства (с this.isSafari = ...
и this.isChrome = ...
).Но на самом деле вам не нужны свойства, только переменные.
Кроме того, вы на самом деле не вызываете downloadFile
из любого места.
Далее, создание новых свойств объекта окна и использование 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");