I Follow Mohamed
I Follow Mohamed

Reputation: 9

Generate goo.gl short URL for current URL automaticlly

I'm new to Google Developer Console and JavaScript too. I want to auto generate a short url for current page url.

I have this working lines with onclick event attribute but I want it generated automaticlly after the page is loaded:

HTML:

<div id='output'>google link display here</div><br/>

<button onclick="makeShort();">create shorten link</button>

JS:

    function makeShort() 
    {
   var pageURL=window.location.href;
        var request = gapi.client.urlshortener.url.insert({
        'resource': {
          'longUrl': pageURL
        }
        });
        request.execute(function(response) 
        {

            if(response.id != null)
            {
                str ="<b>Short URL:</b> <a href='"+response.id+"'>"+response.id+"</a><br>";
                document.getElementById("output").innerHTML = str;
            }
            else
            {
                alert("error: creating short url");
            }

        });
     }
        $(window).load(function load()
    {
     gapi.client.setApiKey('AAAAaaaa_XXXXXXxxxx'); //here my API KEY
     gapi.client.load('urlshortener', 'v1',function(){});

    });

I suppose the function should look like this:

shortThis(window.location.href);

or

shortThis('https://www.google.com');

Upvotes: 0

Views: 772

Answers (1)

lukevp
lukevp

Reputation: 715

You just need to add an onload to your body that will call your function whenever your page is loaded.

For example,

<body onload="makeShort()">

Upvotes: 1

Related Questions