简体   繁体   中英

Downloading VCF file on iPhone browser

I am trying to download a vcf file in my mobile web app, without hitting the server.

 function downloadVcf(filename, data) {
    var element = document.createElement('a');
    element.setAttribute('href', 'data:text/x-vcard;charset=utf-8,' + encodeURIComponent(data));
    element.setAttribute('download', filename);

    element.style.display = 'none';
    document.body.appendChild(element);

    element.click();

    document.body.removeChild(element);
  }

The code above works very well while debugging on chrome browser with windows OS. Also it works perfectly fine on chrome browser on android phones. But it does not work on iPhone browser (safari). Instead of downloading the vcf file it opens the VCF file in browser. But it does have option for user to import it to other apps (contacts for instance). But what I want is to download the VCF file in user's iPhone.

Please help.

Setting document.location.href to the value of your data URI should work:

function downloadVcf(data) {

    // build data url
    var url = 'data:text/x-vcard;charset=utf-8,' + encodeURIComponent(data);

    // ask the browser to download it
    document.location.href = url;
}

Since vCard Specification 4, the mime type text/x-vcard is deprecated. Only the mime type text/vcard (without x-) is valid. Check if iOS browsers do fail because of the mime type in the beginning of your data url.

For me it worked like this: (Chrome, Firefox, Edge, Android and Iphone)

var name = $('.people-name').text().replace(/\s+/g, '-').toLowerCase();

var vcard = vcard_begin+name+cel+tel+address+email+image+vcard_end;
// Create vcard content on variables
/*
Exemple:

var email = 'item1.EMAIL;type=email;type=work,pref:'+ mails + '\nitem1.X-ABLabel:Email\n';

*/
var filename = name + '.vcf';

var myFile = new File([vcard], filename, {type: "text/vcard;charset=utf-8"});

$(".vcard-download").on("click", function () {
 saveAs(myFile);
}

And HTML

<span class="vcard-download">Save my vcard</span>

accepted answer doesn't work for downloading file with specific file name

function downloadVcf(filename){
     var vcfString="BEGIN:VCARD\nVERSION:3.0\nREV:2022-12-30T05:56:13Z\nN;CHARSET=utf-8:sifr software\nEMAIL;INTERNET:masoomsanadi@yahoo.co.uk\nTEL:+91 9960706060\nADR:kolhapur, maharashtra, india\nEND:VCARD";
     var blob = new Blob([vcfString], {type: 'text/x-vcard'});
     var downloadUrl = URL.createObjectURL(blob);
     var a = document.createElement("a");
     a.href = downloadUrl;
     a.download = filename+".vcf";
     document.body.appendChild(a);
     a.click();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM