Bas Mienis
Bas Mienis

Reputation: 109

Whatsapp: Un able to share current link with Javascript

i am trying to share the current link in whatsapp by using the following javascript and HTML

<script language="javascript">
    function waCurrentPage(){
        return "whatsapp://send?text=Check this out: "+'http://' +
        window.location.hostname + window.location.pathname;
   }
</script>


<a  class="btn btn-social-icon btn-whatsapp" href="javascript:waCurrentPage()" 
    data-action="share/whatsapp/share"><i class="fa fa-whatsapp"></i>
</a>

I have have no idea why it is not working i am getting this output in a browser after pressing the button:

whatsapp://send?text=Check this out: http://bggressive.nl/test/index.html

Upvotes: 4

Views: 4521

Answers (3)

Fabiano Coitinho
Fabiano Coitinho

Reputation: 1

Below is an example function to forward the current url to the Whatsapp API:

function getURL() {
    open(encodeURI("https://api.whatsapp.com/send?text="+window.location.href));
}
 
<button type="button" onclick="getURL();">Whatsapp</button>

Upvotes: 0

warch
warch

Reputation: 2609

try this:

<a class="btn btn-social-icon btn-whatsapp" href="javascript:window.location=waCurrentPage();">Link</a>

JS:

waCurrentPage = function() {
   return encodeURI("whatsapp://send?text=Check this out: " + 'http://' + window.location.hostname + window.location.pathname);
}

https://jsfiddle.net/7ny07Lfw/19/

Upvotes: 2

TechnicalTophat
TechnicalTophat

Reputation: 1725

I know this is a bit more wordy than you want, but it works, and you can also add custom css.

$(document).ready(function() {
    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },

        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    $(document).on("click", '.whatsapp', function() {
            if( isMobile.any() ) {

                var text = $(this).attr("data-text");
                var url = $(this).attr("data-link");
                var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
                var whatsapp_url = "whatsapp://send?text=" + message;
                window.location.href = whatsapp_url;
            } else {
                alert("Please share this article in mobile device");
            }

        });
    });

Upvotes: 1

Related Questions