在Internet Explorer 11中单击链接的权限被拒绝

Nil*_*mat 8 javascript jquery internet-explorer angularjs internet-explorer-11

我修改了一个现有的AngularJS-App,它通过添加一个按钮来列出客户,该按钮允许将客户信息下载为vcard.我点击即可直接在Javascript中创建vcard.下载按钮在单击时调用以下函数,其中customer-item为参数:

function transcodeToAnsi(content){
  var encoding = "windows-1252";
  var nonstandard = {NONSTANDARD_allowLegacyEncoding: true};
  return new TextEncoder(encoding, nonstandard).encode(content);
}

$scope.download = function(item) {
  var filename = 'contact.vcf';
  var aId = "vcard";

  var content = createVCard(item);
  var encoded = transcodeToAnsi(content);

  var blob = new Blob([ encoded ], { type : 'vcf' });
  var url = (window.URL || window.webkitURL).createObjectURL(blob);

  $("body").append('<a id="' + aId + '" href="' + url + '" download=' + filename + ' class="hidden"></a>');
  $timeout(function(){
    document.getElementById(aId).click();
    $("#" + aId).remove();
  })

  return false;
}
Run Code Online (Sandbox Code Playgroud)

在createVCard-function中,我只是将文件内容创建为String,因此不应该进入问题.转码由此库完成:https://github.com/inexorabletash/text-encoding

该功能在Firefox和Chrome中没有问题,但在IE11中没有.控制台中给出以下错误:

Error: Permission denied
at Anonymous function (http://***/Contacts2015/js/contacts.js:169:9)
at Anonymous function (http://***/static/9bojdXAkdR8XdVMdSTxZAgzEwGWhHMwgpuONdU2Y8F4.js:14305:11)
at completeOutstandingRequest (http://***/static/9bojdXAkdR8XdVMdSTxZAgzEwGWhHMwgpuONdU2Y8F4.js:4397:7)
at Anonymous function (http://***/static/9bojdXAkdR8XdVMdSTxZAgzEwGWhHMwgpuONdU2Y8F4.js:4705:7) undefined
Run Code Online (Sandbox Code Playgroud)

第169行是上述函数的指令:

document.getElementById(aId).click();
Run Code Online (Sandbox Code Playgroud)

在控制台中手动输入此语句时,会显示相同的错误.

我很感激每一个关于原因的暗示,甚至更好的解决方法.

编辑

修正了错误行和拼写错误.

小智 19

您无法在Microsoft IE中直接打开Blob.你必须使用window.navigator.msSaveOrOpenBlob.还有msSaveBlob,如果这就是你所需要的.

$scope.download = function() {
    //etc... logic...
    var blob = new Blob([encoded], {type: 'vcf'});

    //for microsoft IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { //other browsers
        var a = document.createElement('a');
        a.style = "display:none";
        a.href = URL.createObjectURL(blob);
        a.download = "filename.jpg";
        a.click();
    }
}
Run Code Online (Sandbox Code Playgroud)

最后一件事:以前的代码不能在firefox上运行,因为firefox不支持click().您可以prototype使用此代码段执行此操作:

HTMLElement.prototype.click = function() {
   var evt = this.ownerDocument.createEvent('MouseEvents');
   evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
   this.dispatchEvent(evt);
}
Run Code Online (Sandbox Code Playgroud)