想要将whatsapp添加到next.js响应式网站

问题描述 投票:0回答:1

我想将 Whatsapp 添加到 next.js 响应式网站。我已经放置了一个图标,当在桌面视图上单击图标时,它会打开 Whatsapp 网站。这是预期的行为。

我希望如果有人在移动设备上查看网站并且用户单击 Whatsapp 图标,它应该打开已安装的 Whatsapp 应用程序实例。

我编写的代码,在移动视图中单击时打开whatsapp网站。 下面是代码。

'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
reactjs next.js whatsapp whatsapi
1个回答
0
投票

navigator.userAgent
不会告诉您用户的设备上是否安装了 Whatsapp。如果任何网站能够找到用户设备上安装的应用程序,这将是一个安全问题。它仅返回浏览器的用户代理字符串

您可以使用 wa.me 链接,它会自动重定向/提示用户重定向到应用程序(请参阅 wa.me 链接的文档)。我会推荐这个,因为它可以处理很多不同的场景,包括桌面应用程序本身。

另一种方法是在确认设备类型之后使用

whatsapp://
链接。像这样的东西:

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

您可以在this stackoverflow 答案中找到列出的一系列方法。

请注意,在 wa.me 链接中,您应该添加不带任何前导零的国家/地区代码或

+

© www.soinside.com 2019 - 2024. All rights reserved.