6

我通過添加一個按鈕來修改現有的AngularJS應用程序,該應用程序列出客戶,該按鈕允許將客戶信息作爲電子名片下載。我通過點擊直接在Javascript中創建vcard。下載按鈕調用點擊與客戶項目下面的函數作爲參數:在Internet Explorer 11中單擊鏈接的權限被拒絕

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; 
} 

在createVCard功能我剛剛創建該文件的內容作爲一個字符串,因此它不應該進入的問題。代碼轉換由此庫完成: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 

線169高於所述功能的指令:顯示

document.getElementById(aId).click(); 

同樣的錯誤,當該語句手工輸入在控制檯中。

我會很感激每個提示的原因,甚至更好的解決方法。

EDIT

校正的誤差行和錯字。

+0

這是因爲你的附加'aId'鏈接到DOM可能是一個問題 - 這可能是因爲它是不知道如何再次將其刪除。我建議看看去除DOM附加元素,也許這會有所幫助。 – Forest

+0

@Furze對不起,我的錯。我打印了錯誤的一行......我改變了它。 –

+0

嘗試將'document.getElementById(aId).click();'改爲'$(「#」+ aId).trigger(「click」);'。 – Forest

回答

12

您不能直接在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(); 
    } 
} 

最後一兩件事:以前的代碼將無法在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); 
} 
+0

謝謝一堆。這樣做! –

+0

謝謝!我一直在試圖解決類似的問題幾個小時。爲了讓你知道,從現在的版本5開始,firefox已經支持HTMLElement上的.click方法。 –