繁体   English   中英

使用javascript在Google Chrome扩展程序中访问Google的网址缩短API

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

我正在编写我的第一个谷歌浏览器扩展程序,它将使用谷歌的URL缩短器api来缩短Chrome中当前活动选项卡的URL。

我是一个长期的开发人员(asm / C ++),但对这个“webby”的东西来说是全新的。 :)

我似乎无法弄清楚如何使用js或jquery制作(然后处理)http POST请求。 我想我只是不理解curl示例之外的POST机制。

我的javascript文件目前看起来像这样:

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

});

最简单的解决方案是使用jquery的$.ajax函数。 这将允许您异步将内容发送到谷歌。 当数据返回时,您可以继续处理响应。

代码看起来像这个问题

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

这是jquery ajax api

2016年1月更新 :这不再有效,因为链接缩短API 现在需要身份验证

我用一个简单的解决方案写了一篇博文: http//uihacker.blogspot.com/2013/04/javascript-use-googl-link-shortener.html

它异步加载Google客户端API,然后在加载链接缩短服务时使用另一个回调。 加载服务后,您可以再次调用此服务。 为简单起见,我只缩短了演示的一个URL。 您似乎不需要API密钥来简单地缩短URL,但是对此服务的某些调用需要一个。 这是基本版本,应该适用于现代浏览器。

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

在这里,我将解释如何使用javascript和html在每个网页上自动创建一个google url缩短器

阶段是

1)如果已经进入第二阶段,请确保您有一个jquery脚本代码。

2)在jquery脚本代码之后或之下添加以下脚本代码:

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

3)如何使用它:

如果要使用html标签超链接

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

如果要使用html标签输入

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




最终的结果

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>

要么

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

DEMO

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

在这个问题上制定了快速简单的解决方案。 希望它能解决问题。

<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>

需要使用正确的密钥替换[GOOGLE API KEY]

您的LongUrl应该替换Url值,即http://example.com

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM