Sunday, September 23, 2012

Example to use google urlshortener

source code
var sUrl={
    fn:null,
    url:'',
    create:function(u,cb){
        sUrl.fn=null;
        sUrl.url='';
        sUrl.fn=setInterval(function(){
            if(sUrl.url!=''){
                sUrl.clear();
                cb(sUrl.url);
                return;
            }
            sUrl.get(u);
        },500);
    },
    get:function(u){
        if(sUrl.url!=''return;
        var request=gapi.client.urlshortener.url.insert({'resource':{'longUrl':u}});
        request.execute(function(resp){
            if(typeof(resp.id)!='undefined'){
                sUrl.url=resp.id;
            }
            else{
                sUrl.url=u;
            }
        });
    },
    clear:function(){
        clearInterval(sUrl.fn);
    }
};

example (http://jsfiddle.net/ueszM/1/)
<script>
function initGAPI(){
    gapi.client.load('urlshortener''v1');
}

function getUrl(){
    sUrl.create(document.getElementById('url').value,function(u){
        alert(u);
    });
}

</script>
<script src="https://apis.google.com/js/client.js?onload=initGAPI"></script>

<input id="url" value="http://www.google.com" />
<href="#" onclick="getUrl();return false;">get url</a>

No comments:

Post a Comment