jQuery on the fly URL shortener
Asked Answered
B

6

18

I'm looking for an on the fly URL shortener much like how tweetdeck works. I have found many jQuery and general javascript plugins that take a url and run it through a shortening service such as bit.ly when a button is pressed. However, I have not been able to find one that does it on the fly. My first question is does this already exist someplace? Secondly, if it doesn't, then what would be the best way to recognize a URL that needs to be shortened inside a textbox? My thoughts:

  1. On onKeyUp of that text area run through the text looking for http
  2. If found grab the whole URL (how do I determine the end? could be period, comma, space, etc...)
  3. Make sure the URL isn't already a bit.ly URL
  4. Validate the URL (make a request and make sure the http response is not an error, does bit.ly already do this?)
  5. If valid, send the url to bit.ly's API and get the response
  6. Replace the long URL with the short URL in the text area.

Thoughts?

Brassica answered 20/11, 2009 at 15:52 Comment(3)
Not sure what you'll be using this for but if you're going to have users inputting data, you might want to expand step 3 to include more URL shortening services than just bit.ly. Unless you're alright with a bit.ly address redirecting to a tinyurl.com address (for example) redirecting to the final destination.His
Instead of making sure it isn't a bit.ly URL, you can shorten just the URLs that are longer than x characters. Today tinyurl.com uses 27 characters, for example.Medicament
earcar where are you finding the min lengths for different services?Brassica
A
18

Here is an example how to get a shortened URL with Bitly API and jQuery:

function get_short_url(long_url, login, api_key, func)
{
    $.getJSON(
        "http://api.bitly.com/v3/shorten?callback=?", 
        { 
            "format": "json",
            "apiKey": api_key,
            "login": login,
            "longUrl": long_url
        },
        function(response)
        {
            func(response.data.url);
        }
    );
}

The following code could be used to get a short URL:

/*
Sign up for Bitly account at
 https://bitly.com/a/sign_up

and upon completion visit
https://bitly.com/a/your_api_key/ 
to get "login" and "api_key" values
*/
var login = "LOGIN_HERE";
var api_key = "API_KEY_HERE";
var long_url = "http://www.kozlenko.info";

get_short_url(long_url, login, api_key, function(short_url) {
    console.log(short_url);
});
Anstice answered 10/8, 2011 at 3:49 Comment(1)
The Bitly API has changed. See my answerCitation
C
8

I guess the API of Bitly has changed slightly. You now only really need an access token to request a short URL.

Following the best practices, I created the following Javascript-only snippet:

getShortUrl: function(url, callback)
{
   var accessToken = '___YOUR_ACCESS_TOKEN___';
   var url = 'https://api-ssl.bitly.com/v3/shorten?access_token=' + accessToken + '&longUrl=' + encodeURIComponent(url);

    $.getJSON(
        url,
        {},
        function(response)
        {
            if(callback)
                callback(response.data.url);
        }
    );
},
Citation answered 27/2, 2014 at 9:22 Comment(0)
L
4

The on the fly bit is going to be difficult to make reliable and speedy.

People won't type http most of the time or even www.

The end, like you said, is going to be hard to determine if the url contains a space or worse, runs into the next sentence because the user didn't put in a space.

And what if people need to change the url after the fact because they typed http://stakoverflow.com/ instead of https://stackoverflow.com/ ?

I think the best solution would be an "insert shortened url" button on your text editor that allowed people to do just that. Or, do it server-side when the post is made.

Lilias answered 20/11, 2009 at 16:12 Comment(1)
the post has a max length and shortening on the fly gives them more characters to make their postBrassica
T
4

You could also generate a short url with php and curl on the server, this way you don't have to expose your API key in the webpage:

<?php
    //the long url posted by your webpage
    $url = strip_tags($_POST["url"]);

    $api_user = "your_bitly_user_name";
    $api_key = "your_bitly_api_key";

    //send it to the bitly shorten webservice
    $ch = curl_init ("http://api.bitly.com/v3/shorten?login=$api_user&apiKey=$api_key&longUrl=$url&format=json");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //the response is a JSON object, send it to your webpage
    echo curl_exec($ch);    
?>

Then in your webpage the code should be something like:

    //the long url that you want to shorten
    var longUrl = escape(window.location.href)

    $.ajax({
        url : "php/getShortUrl.php",//this is the php script above
        dataType : "json",
        type : "POST",
        data : {
            url : longUrl
        },
        success : function(data) {
            if(data.status_txt === "OK"){
                shortUrl = data.data.url;
            }
        },
        error : function(xhr, error, message) {
            //no success, fallback to the long url
            shortUrl = longUrl
        }
    });

See the bitly API for more details

Topdrawer answered 15/10, 2011 at 10:36 Comment(0)
F
0

Why not do a jQuery POST to the Bit.ly API? http://blog.themeforest.net/tutorials/creating-an-ajax-web-app-using-the-bitly-api/

Flatting answered 20/11, 2009 at 19:2 Comment(1)
the problem is that they can only have X number of characters in their post and shortening their URL on the fly gives them extra charactersBrassica
S
0

I found your post while looking for something similar and eventually just wrote a jQuery plugin that provides (at least part of) what you're looking for.

My jQuery Url Shortener on Bitbucket

It's a very simple plugin; I didn't need to shorten the user's urls so I don't have any length checking or url testing before shortening it, though I am not averse to adding those types of features.

Just thought you might find it useful.

As for Recognising URLs in your textbox, I would suggest using a RegEx to match the url.

Slippery answered 19/3, 2010 at 14:23 Comment(1)
Hi Jiaaro - I used this and had to make a small change to support URL encoding. Change line 6 to: +"&longUrl="+encodeURIComponent(longUrl) - thanks for the useful plugin.Yeaton

© 2022 - 2024 — McMap. All rights reserved.