Google APIs Client Library for JavaScriptを使うと、ブラウザだけで goo.gl の短縮URLを作成できます。
準備
- Google APIs ダッシュボードでプロジェクトを作成する。または既存プロジェクトを選択する。
- 左のメニューからライブラリを選択して、検索欄にurl等と入れるとURL Shortener APIが見つかるので選択する。
- 上部の有効にするを選択する。
- 左のメニューから認証情報を選択して、認証情報を作成→APIキーと選択してAPIキーを作成する。
Firebaseで作成したプロジェクトを使うこともできます。
実装
まずGoogle APIs Clientを読み込みます。HTML内に<script src="https://apis.google.com/js/api.js"></script>
を書けばOKです。
<html>
<head>
<!-- Google APIs Client -->
<script src="https://apis.google.com/js/api.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
次に、このライブラリを使って短縮URLを生成する関数を作成します。url-shortener.js
というファイルを作成して、以下のコードを記述します。
url-shortener.js
function shorten(url) {
return new Promise((resolve, reject) => {
gapi.load('client', _ => {
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
'discoveryDocs': ['https://www.googleapis.com/discovery/v1/apis/urlshortener/v1/rest'],
})
.then(_ => gapi.client.urlshortener.url.insert({
longUrl: url
}))
.then(resolve, reject)
});
});
}
YOUT_API_KEY
は、先程作成したAPIキーに置き換えてください。
そしてこれを先程のGoogle APIs Clientの読み込みの後に加えます。
<html>
<head>
<!-- Google APIs Client -->
<script src="https://apis.google.com/js/api.js"></script>
<!-- shorten 関数 -->
<script src="url-shortener.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
あとは、shorten(url)
関数を呼べば、短縮URLのレスポンスがPromise
オブジェクトで取得できます。
<html>
<head>
<!-- Google APIs Client -->
<script src="https://apis.google.com/js/api.js"></script>
<!-- shorten 関数 -->
<script src="url-shortener.js"></script>
</head>
<body>
<h1>Hello World</h1>
<div id="shortUrlOutput"></div>
<script>
// 短縮URLを取得する
shorten('http://www.eje-c.com')
.then(function(response) {
// response.result.id に短縮URLが入っている
var shortUrl = response.result.id;
// 画面に表示
document.getElementById('shortUrlOutput').innerHTML = shortUrl;
});
</script>
</body>
</html>