使用JavaScript在谷歌浏览器扩展程序中访问谷歌的URL缩短器API [英] Using javascript to access Google's URL shortener APIs in a Google Chrome extension

查看:208
本文介绍了使用JavaScript在谷歌浏览器扩展程序中访问谷歌的URL缩短器API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在撰写我的第一个Google Chrome扩展程序,该扩展程序将使用 Google的URL缩短器API 缩短Chrome浏览器中的当前活动选项卡的URL。



我是一位长期的sw开发人员(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以
的形式发送http post请求// POST https://www.googleapis.com/urlshortener/v1/url
// Content-Type:application / json
// { longUrl:http://www.google.com/}
});



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



代码看起来像这个问题

  $。ajax({
url:'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
类型:'POST',
contentType:'application / json; charset = utf-8',
data:'{longUrl:''+ longURL +'}',
dataType: 'json',
success:function(response){
var result = JSON.parse(response); //评估J-Son响应对象。
}
}) ;

以下是 jquery ajax api


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

});

解决方案

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

这篇关于使用JavaScript在谷歌浏览器扩展程序中访问谷歌的URL缩短器API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆