'Open vCard with Javascript

With a QR code vcard, the user scans the code with their phone and then the dialog with the "add to contacts" pops up on their phone, such as the code below:

enter image description here

How can I do the same but instead of a QR code scan, I want it to do the same with a button click.

I have tried the following:

var btn = document.getElementById(“clickMe”);
btn.addEventListener(“click”, loadvcard);
function loadvcard(){
 url = "BEGIN%3AVCARD%0AVERSION%3A3.0%0AN%3ADoe%3BJohn%0AFN%3AJohn%20Doe%0ATITLE%3A08002221111%0AORG%3AStackflowover%0AEMAIL%3BTYPE%3DINTERNET%3Ajohndoe%40gmail.com%0AEND%3AVCARD";
 window.open(url);

}


Solution 1:[1]

You can open your vcard in the browser as a data url if you want.

Your code would be:

var btn = document.getElementById(“clickMe”);
btn.addEventListener(“click”, loadvcard);
function loadvcard(){
 var data = "BEGIN%3AVCARD%0AVERSION%3A3.0%0AN%3ADoe%3BJohn%0AFN%3AJohn%20Doe%0ATITLE%3A08002221111%0AORG%3AStackflowover%0AEMAIL%3BTYPE%3DINTERNET%3Ajohndoe%40gmail.com%0AEND%3AVCARD";
 window.open("data:text/x-vcard;urlencoded," + data);
}

Solution 2:[2]

Try to use the web share api, it works.

<html>
<title>
    Web Share API
</title>

<body>
    <div>
        <div>
            <button onclick="shareVcard" id="shareFilesButton">Share Files</button>
        </div>
    </div>
</body>
<script>
    document.getElementById('shareFilesButton').addEventListener("click", () => shareVcard())

function shareVcard() {
fetch("sample.vcf")
.then(function(response) {
    return response.text()
  })
.then(function(text) {

    var file = new File([text], "sample.vcf", {type: 'text/vcard'});
    var filesArray = [file];
    var shareData = { files: filesArray };


    if (navigator.canShare && navigator.canShare(shareData)) {

    // Adding title afterwards as navigator.canShare just
    // takes files as input
    shareData.title = "vcard";

    navigator.share(shareData)
    .then(() => console.log('Share was successful.'))
    .catch((error) => console.log('Sharing failed', error));

    } else {
    console.log("Your system doesn't support sharing files.");
    }
 
});
    }
</script>

</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Max1Truc
Solution 2 Romilton Lima