【问题标题】:Using javascript to access Google's URL shortener APIs in a Google Chrome extension在 Google Chrome 扩展程序中使用 javascript 访问 Google 的 URL 缩短 API
【发布时间】:2012-10-02 19:11:44
【问题描述】:

我正在编写我的第一个 google chrome 扩展程序,它将使用 Google's URL shortener 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/"}
});

});

【问题讨论】:

    标签: javascript jquery google-chrome-extension http-post goo.gl


    【解决方案1】:

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

    代码类似于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.
            }
         });
    

    这里是jquery ajax api

    【讨论】:

    • 非常感谢您的回复!这正是我一直在寻找的(即使是像我这样的菜鸟也很有意义)。 :) 当此代码执行时,谷歌会回复以下内容。你能理解这个吗? TIA { "error": { "errors": [ { "domain": "global", "reason": "parseError", "message": "此 API 不支持解析表单编码输入。" } ], "code": 400, "message": "此 API 不支持解析表单编码的输入。" } }
    • 这似乎是数据类型的问题,但我不确定确切的解决方案。 Here is a discussion on google groups
    【解决方案2】:

    2016 年 1 月更新:这不再有效,因为链接缩短 API requires authentication now

    我用一个简单的解决方案写了一篇博文: 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>');
    

    【讨论】:

      【解决方案3】:

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

      阶段阶段是

      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

      【讨论】:

      • 你应该在你的答案中添加一个解释。
      【解决方案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】:

        针对这个问题制定了一个快速简单的解决方案。希望能解决问题。

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

        需要用正确的Key替换[GOOGLE API KEY]

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

        【讨论】:

        • 投反对票,因为由于内容安全策略限制,您的解决方案并不能真正轻松地应用于 Chrome 扩展程序。
        猜你喜欢
        • 2020-04-14
        • 2010-11-29
        • 1970-01-01
        • 2013-11-20
        • 2014-03-21
        • 2017-03-08
        • 2012-01-09
        • 1970-01-01
        相关资源
        最近更新 更多