Savaratkar
Savaratkar

Reputation: 2084

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.

Upvotes: 3

Views: 5820

Answers (4)

sifr_dot_in
sifr_dot_in

Reputation: 3603

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:[email protected]\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();
}

Upvotes: 0

Carlos Volp
Carlos Volp

Reputation: 31

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>

Upvotes: 1

Christoph Bimminger
Christoph Bimminger

Reputation: 1018

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.

Upvotes: 3

John Doherty
John Doherty

Reputation: 4105

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

Upvotes: 5

Related Questions