Ujjawal Bhandari
Ujjawal Bhandari

Reputation: 1372

Send whatsapp message via JS

I want to send message to a specific number directly. I tried a couple of methods but no success.

First Method It opens Whatsapp web. I want it directly to the mobile whatsapp number.

function send_handle(){

  let num=document.getElementById("number").value;

  let msg= document.getElementById("msg").value;

    let name= document.getElementById("name").value;
  
  var win = window.open(`https://wa.me/${num}?text=I%27m%20api%20msg%20hello%20${name}%20friend%20${msg}`, '_blank');
 // win.focus();
}
        <div>
          <h3>whatsapp send app </h3>
            <h6>add number without space like 17272912606 not <strike>+1 (727) 2912606 </strike></h6>
  <input id="number" type="numric" placeholder="phone 966506666666" >
   <input id="name" type="text" placeholder="name" >
   <input id="msg" type="text" placeholder="type msg" >
<button onclick="send_handle()">send</button>
</div>

Second Method : whatsappWebJs Not showing anything

import * as whatsappWebJs from "https://cdn.skypack.dev/whatsapp-web.js";
const { Client } = whatsappWebJs;
const client = new Client();

client.on('qr', (qr) => {
    // Generate and scan this code with your phone
    console.log('QR RECEIVED', qr);
});

client.on('ready', () => {
 console.log('Client is ready!');

  // Number where you want to send the message.
 const number = "+91********";

  // Your message.
 const text = "Hey john";

  // Getting chatId from the number.
  // we have to delete "+" from the beginning and add "@c.us" at the end of the number.
 const chatId = number.substring(1) + "@c.us";

 // Sending message.
 client.sendMessage(chatId, text);
});

Upvotes: 0

Views: 2554

Answers (1)

Victor Vasconcelos
Victor Vasconcelos

Reputation: 21

Seems that you forgot to initialize your client with Whats App Js. Also I would recommend to use qr-terminal for good QR Format.

const qrcode = require("qrcode-terminal");

// Add this for QR format in terminal
client.on('qr', qr => {
     qrcode.generate(qr, { small: true });
});

// rest of your code 

// ....

// Use initialize to start with the client
client.initialize();

Upvotes: 1

Related Questions