I wanted to import a virtual contact file (.vcf) (with a single person’s details on it) directly using Android’s native contact import activity without downloading it first using the browser. This all had to be done when a user clicked on a link in their device’s browser (e.g., Google Chrome).
Usually when a user clicks on the link, it downloads a virtual contact file (.vcf) on their system (for e.g., Android). I wanted to bypass this behaviour and open the intent directly, which the user would have fired manually by navigating to the file (.vcf) and clicking on it.
I tried looking at several questions asked here, such as:
- Android how is a Chrome intent-based URI opened
- What is the intent to launch any website link in Google Chrome
- Launching Intent through Chrome with data
- Adding Contacts to phone via JS
I also checked out Google’s guide on Android Intents with Chrome in Chrome for Android subsection. Available here, last updated on February 28, 2014.
2
Answers
So I'm trying to share my findings on this issue. I know this can be achieved easily using React Native, but I wanted to give it a try using React.js. I found out that:
Without both of the above prerequisites, it's not possible to fire an app's intent from a link in the web browser in Android.
You can do this with react.js easily
Import the navigator object at the top of your component file:
Create a link in your component’s render method that points to the
virtual contact file (.vcf), and give it an ID so you can access it
later in your useEffect hook:
In the useEffect hook, add an event listener to the link that will
trigger the Web Share API when clicked. You’ll also want to remove
the event listener when the component unmounts to prevent memory
leaks.
When the user clicks the link, the event listener will prevent the
default behavior (downloading the file) and trigger the Web Share
API. If the Web Share API is available on the user’s device, it will
launch the native contact import activity with the virtual contact
file. If the Web Share API is not available, nothing will happen.