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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12696704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:54:22  来源:igfitidea点击:

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

javascriptjquerygoogle-chrome-extensionhttp-postgoo.gl

提问by RobertJoseph

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

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

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

我是一个长期的软件开发人员(asm/C++),但对这个“webby”的东西完全陌生。:)

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.

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

My javascript file currently looks like this:

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

});

});

回答by Mark Meyer

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

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

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

这是jquery ajax api

回答by cacheflowe

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

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

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

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

它异步加载 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>');

回答by Quest ID

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

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

Phase-stages are

阶段阶段是

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

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

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

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

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

3) 使用方法:

If you want to use html tags hyperlink

如果要使用html标签超链接

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

If you want to use html tag input

如果要使用html标签输入

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








The end result

最终结果

JavaScript

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

HTML

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

or

或者

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

DEMO

演示

回答by Harish Chilamanthula

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

回答by TRIKONINFOSYSTEMS

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

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

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

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