3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Google URL Shortener をJavaScript (Webページ) で使用する

Last updated at Posted at 2016-12-08

Google APIs Client Library for JavaScriptを使うと、ブラウザだけで goo.gl の短縮URLを作成できます。

準備

  1. Google APIs ダッシュボードでプロジェクトを作成する。または既存プロジェクトを選択する。
  2. 左のメニューからライブラリを選択して、検索欄にurl等と入れるとURL Shortener APIが見つかるので選択する。
  3. 上部の有効にするを選択する。
  4. 左のメニューから認証情報を選択して、認証情報を作成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>
3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?