javascriptshort-url

How to shorten url when sharing a webpage from my website on social media?


How to shorten url when sharing a webpage from my website on social media? I hope it can be done with javascript and apis, I've checked the bitly api, but don't know how to get starting. Thanks.


Solution

  • I have 2 useful resources for you:

    This one for google url shortener: http://www.i-visionblog.com/2014/07/google-url-shortener-api-javascript.html

    And this one for bit.ly: https://bdhacker.wordpress.com/2010/03/30/dynamically-use-bitly-in-your-site-easiest-way/

    First, you need an account on http://bit.ly. To create one, go to the site and register.

    Once you’ve registered, login and go to your Account page. There, you will find your API key.

    Put this in your HTML HEAD:

    <script type="text/javascript" charset="utf-8" src="http://bit . ly/javascript-api.js?version=latest&login=******&apiKey=*****************"></script>
    

    (remove spaces in bit.ly url. stackoverflow doesn't allow to post answers with that url)


    Put this before </body>:

    <script>
        // Bit.ly API
        BitlyCB.shortenResponse = function(data) {
                var sss = '';
                var first_result;
                // Results are keyed by longUrl, so we need to grab the first one.
                for     (var r in data.results) {
                        first_result = data.results[r]; break;
                }
                sss = first_result["shortUrl"].toString();
                document.getElementById("qlink").value = sss;
        }
        BitlyClient.shorten(window.location, 'BitlyCB.shortenResponse');
    </script>
    

    And this, somewhere in your page:

    <h3>Link to this page</h3><br>
    Use this link to tell others about this page! <input onclick = "this.select()" type = 'text' id = "qlink" style = "width:100%;">