6

I am writing my first google chrome extension which will use Google's URL shortener api to shorten the URL of the currently active tab in Chrome.

I am a longtime sw developer (asm/C++) but totally new to this "webby" stuff. :)

I can't seem to figure out how to make (and then process) the http POST request using js or jquery. I think I just don't understand the POST mechanism outside of the curl example.

My javascript file currently looks like this:

chrome.browserAction.onClicked.addListener(function(tab) { 
    console.log('chrome.browserAction.onClicked.addListener');

chrome.tabs.getSelected(null, function(tab) {
    var tablink = tab.url;
    console.log(tablink);

    //TODO send http post request in the form
    // POST https://www.googleapis.com/urlshortener/v1/url
    //   Content-Type: application/json
    //   {"longUrl": "http://www.google.com/"}
});

});

5 Answers 5

5

The easiest solution would be to use jquery's $.ajax function. This will allow you to asynchronously send the content to google. When the data comes back you can then continue to process the response.

The code will look something like this question

$.ajax({
        url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: '{ longUrl: "' + longURL +'"}',
        dataType: 'json',
        success: function(response) {
            var result = JSON.parse(response); // Evaluate the J-Son response object.
        }
     });

Here is the jquery ajax api

2
  • Thank you very much for your response! This is exactly what I was looking for (and makes sense to even a noob like me). :) When this code executes google responds with the following. Does this make sense to you? TIA { "error": { "errors": [ { "domain": "global", "reason": "parseError", "message": "This API does not support parsing form-encoded input." } ], "code": 400, "message": "This API does not support parsing form-encoded input." } } Oct 2, 2012 at 20:11
  • It appears to be a problem with the dataType but I'm not sure of the exact solution. Here is a discussion on google groups
    – Mark Meyer
    Oct 2, 2012 at 21:05
5

Update in Jan, 2016: This no longer works, as the link shortening API requires authentication now.

I wrote a blog post with a simple solution: http://uihacker.blogspot.com/2013/04/javascript-use-googl-link-shortener.html

It asynchronously loads the Google client API, then uses another callback when the link shortener service is loaded. After the service loads, you'd be able to call this service again. For simplicity, I've only shortened one URL for the demo. It doesn't appear that you need an API key to simply shorten URLs, but certain calls to this service would require one. Here's the basic version, which should work in modern browsers.

var shortenUrl = function() {
  var request = gapi.client.urlshortener.url.insert({
    resource: {
      longUrl: 'http://your-long-url.com'
    }
  });
  request.execute(function(response) {
    var shortUrl = response.id;
    console.log('short url:', shortUrl);
  });
};

var googleApiLoaded = function() {
  gapi.client.load("urlshortener", "v1", shortenUrl);
};

window.googleApiLoaded = googleApiLoaded;
$(document.body).append('<script src="https://apis.google.com/js/client.js?onload=googleApiLoaded"></script>');
0

Here I will explain how to create a google url shortener automatically on every web page using javascript and html

Phase-stages are

1) Make sure you have a jquery script code, if there is already advanced to phase two.

2) Add the following script code, after or below the jquery script code:

<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>

3) How to use it:

If you want to use html tags hyperlink

<a id="apireadHref" href="blank">blank</a>

If you want to use html tag input

<input id="apireadValue" value="blank"/>




The end result

JavaScript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
  $.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>

HTML

<a id="apireadHref" href="blank">blank</a>

or

<input id="apireadValue" value="blank"/>

DEMO

1
  • 2
    You should add an explanation to you answer. Feb 1, 2017 at 9:10
0
$.ajax({
        url: 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHf3wIv4T',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        data: '{ "longUrl": "' + longURL +'"}',
        dataType: 'json',
        success: function(response) {
            console.log(response);
        }
     });
0
-1

Worked out a quick and simple solution on this issue. Hope it will solve the problem.

<html>
<head>
<title>URL Shortener using Google API. http://goo.gl </title>
<script src="https://apis.google.com/js/client.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
function load() {
    gapi.client.setApiKey('[GOOGLE API KEY]');
    gapi.client.load('urlshortener', 'v1', function() { 
        document.getElementById("result").innerHTML = "";

        var Url = "http://onlineinvite.in";
        var request = gapi.client.urlshortener.url.insert({
            'resource': {
            'longUrl': Url
            }
        });
        request.execute(function(response) {

            if (response.id != null) {
                str = "<b>Long URL:</b>" + Url + "<br>";
                str += "<b>Test Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
                document.getElementById("result").innerHTML = str;
            }
            else {
                alert("Error: creating short url \n" + response.error);
            }
        });
    });
}
window.onload = load;
</script>
<body>
<div id="result"></div>
</body>
</html>

Need to replace [GOOGLE API KEY] with the correct Key

Your LongUrl should replace Url value i.e. http://example.com

1
  • Downvoting, since your solution doesn't really apply easily in a Chrome extension due to Content Security Policy restrictions.
    – Xan
    Dec 3, 2015 at 21:57

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.