DEV Community

Manda Putra
Manda Putra

Posted on • Updated on

Click to send on WhatsApp with JavaScript

IMPORTANT, Please encodeURIComponent()

TL;DR You can use link below and place it on your button, or whatever. Its simply will open up whatsapp on user phone. But it isn't automatically send.

https://api.whatsapp.com/send?phone=+*YOURNUMBER*&text=%20*YOURMESSAGE*

What we were built here it is a dynamic send to WhatsApp link with JavaScript approach you can use the link above and give it a try

Okay I'll use JSBin with this, first open up then its just easy you will use split() and join() string property on JavaScript here my script.

// https://api.whatsapp.com/send?phone=+{{ *YOURNUMBER* }}&text=%20{{ *YOUR MESSAGE* }}

var yourNumber = "{{ your number in string}}"
var yourMessage = "{{ your message in string }}"

// %20 mean space in link
// If you already had an array then you just join them with '%20'
// easy right

function getLinkWhastapp(number, message) {
  number = yourNumber
  message = yourMessage.split(' ').join('%20')

  return console.log('https://api.whatsapp.com/send?phone=' + number + '&text=%20' + message)
}

getLinkWhastapp()
Enter fullscreen mode Exit fullscreen mode

Copy that on jsbin, give phone number and message do you want, make sure you use WhatsApp, It will open up WhatsApp on your phone with the message you wrote.

Further reading :


Important

This post was made to learn JS split and join for production purpose you should use encodeURIComponent()

function getLinkWhastapp(number, message) {
  var url = 'https://api.whatsapp.com/send?phone=' 
     + number 
     + '&text=' 
     + encodeURIComponent(message)

  return url
}
Enter fullscreen mode Exit fullscreen mode

Oldest comments (10)

Collapse
 
gypsicoder profile image
Bishnu Pada Chanda

Is there any way to send image with text?

Collapse
 
mandaputtra profile image
Manda Putra

No man its only accept url

Collapse
 
programmer285 profile image
programmer285

Then maybe we can send url of Image?

Thread Thread
 
mandaputtra profile image
Manda Putra

Yes you can but it will convert to url text, not an image.

Thread Thread
 
programmer285 profile image
programmer285

Ok, Thanks for reply

Thread Thread
 
rajkashyap16 profile image
rajkashyap16

How can i use this for taking orders from our website ...like this👇
blantertokoshop.blogspot.com/2019/...

Collapse
 
karanjalight profile image
Paul Karanja

Yeah, maybe converting URLs to images should be a feature on Whatsapp.

Thread Thread
 
ruthmoog profile image
ruthmoog

Maybe media attribute link might work for this? There is preview url too

whatsapp cloud api docs: messages - media object

Collapse
 
gustavosfq profile image
Gustavo Flores

maybe use encodeURIComponent() to encode this.message to URI

Collapse
 
mandaputtra profile image
Manda Putra

Yeah thats nice, easy, error prone