Using javascript to access Google's URL shortener APIs in a Google Chrome extension

穿精又带淫゛_ 提交于 2019-12-23 09:04:09

问题


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/"}
});

});


回答1:


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:


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>');



回答3:


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




回答4:


$.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);
        }
     });



回答5:


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



来源:https://stackoverflow.com/questions/12696704/using-javascript-to-access-googles-url-shortener-apis-in-a-google-chrome-extens

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!