Want to add whatsapp to next.js responsive website

1.1k views Asked by At

I want to add whatsapp to next.js responsive website. I have put an icon and when icon is clicked on desktop view it opens whatsapp web. which is expected behaviour.

I want if someone is viewing the website on mobile and user clicks the whatsapp icon it should open installed whatsapp app instance.

The code which I have written, it is opening whatsapp website when clicked in mobile view. Below is the code.

'use client'

import React from 'react'
import { useRouter } from 'next/navigation'
import { FaWhatsapp } from 'react-icons/fa6'


const Whatsapp = () => {

  const router = useRouter();

  const handleClick = async () => {

    // Check if WhatApp installed, if yes open whatsapp else open whatsapp web

    if (navigator.userAgent.includes('WhatsApp')) {
      // WhatsApp is installed
      window.open(`whatsapp://send?phone=8879xxxxxx`)
    } else {
      // WhatsApp is not installed, open WhatsApp Web
      window.open('https://web.whatsapp.com/send?phone=8879xxxxxx', '_blank');
    }
  }

  return (
    <>
      <div className='bg-green-600 w-min p-2 rounded-full fixed 
          bottom-10 right-4 cursor-pointer md:right-8' onClick={handleClick}>
        <FaWhatsapp color='white' className='w-7 h-7 md:w-10 md:h-10' />
      </div>
    </>
  )
}

export default Whatsapp
1

There are 1 answers

2
AviusX On

navigator.userAgent will not tell you whether a user has Whatsapp installed on their device. It would be a security issue if any website could find out the apps installed on a user's device. It only returns the user agent string for the browser.

You could use the wa.me links which automatically redirect / prompt the user to redirect to the app (see docs for wa.me links). I would recommend this since this handles a lot of different scenarios including desktop app ones itself.

Another way would be to use the whatsapp:// links but after confirming the device type. Something like this:

const isAndroid = navigator.userAgent.toLowerCase().indexOf("android") !== -1;

You can find a bunch of approaches listed in this stackoverflow answer.

Do note that in the wa.me links you should add the country code without any leading zeroes or +.