Search code examples
javascriptwhatsapp

Sending JavaScript array data to WhatsApp contact via link


I have a javascript array. Example:

let newArrVal = [{"name" : "book",
"Price" : 18.99}, {"name" : "bag",
"Price" : 18.99}]

I have an HTML button and I want that HTML button to send this array of objects data to WhatsApp, how do I do it? If you want to send a message to WhatsApp, you should have &20 for the space separator. For example wa.me/+1234455?text=hello%20world

Here is my code :

 function sendShoppingListToWhatsApp() {
    const shoppingList = cart.map(item => `${item.name.replace(/\s/g, '%20')}: $${item.price.toFixed(2)}`).join('%0A');
    const totalAmount = total.toFixed(2);

    const message = `Shopping%20List:%0A${shoppingList}%0ATotal:%20$${totalAmount}`;

    const whatsappURL = `https://wa.me/+6285271926369?text=${encodeURIComponent(message)}`;
    // window.open(whatsappURL, '_blank');
  console.log(whatsappURL)
}

I don't understand why it says Whatsapp API blocked


Solution

  • It would be best if you used the encodeURIComponent() method, where the return value is a new string representing the provided uriComponent encoded as a URI component. Also, the JSON.stringify() method to convert the array into JSON string.

    See it in this example:

    (function() {
      let newArrVal = [{
        "name": "book",
        "Price": 18.99
      }, {
        "name": "bag",
        "Price": 18.99
      }]
    
      let urlEncodedData = encodeURIComponent(JSON.stringify(newArrVal));
      console.log(urlEncodedData); // This data may be sent through a URL.
    }());
    .as-console-wrapper {
      top: 0;
    }

    So, in the example above, you will see the URL encoded version of your array in the console.

    Now, if you need to decode back your data, you may use the decodeURIComponent() method.

    (function() {
      let urlEncodedData = "%5B%7B%22name%22%3A%22book%22%2C%22Price%22%3A18.99%7D%2C%7B%22name%22%3A%22bag%22%2C%22Price%22%3A18.99%7D%5D";
    
      let urlDecodedData = decodeURIComponent(urlEncodedData);
    
      console.log(urlDecodedData);
    }());
    .as-console-wrapper {
      top: 0;
    }