inputボックスにURL打ち込むと自動URL短縮化されるjs
[f:id:kenzo0107:20160310115924p:plain]
概要
最近では URL に日本語を利用するケースが増えてきました。
SEO として価値がある作業かどうかは眉唾ではありますが
ネット利用率の低い方にとっては UI としては分かりやすいのかもしれません。
その点を論じているブログがありました。
日本語を含む URL を Twitter へ投稿するようなソーシャル連携ツール等の開発の際、
文字数に厳密に注意する必要があり、短縮の自動化を bitly API で行いましたので
そのまとめです。
手順
bitly.com に登録する
[https://bitly.com/a/oauth_apps]にて
Access Token
を取得
- 以下 js を html 等でロードしてください。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# [bitly Generic Access Token] は https://bitly.com/a/oauth_apps より 生成してください。 | |
# | |
# 以下のようなinputボックスを想定しています。 | |
# <input type="text" name="hogehoge" value="" class="bitly"> | |
var generateUrl = (function () { | |
// 短縮化するURLの文字列数. 以下の場合30文字未満の場合短縮化しない。 | |
var SHORTEN_URL_LENGTH = 30; | |
// フォームから値を取得 | |
function getUrl() { | |
$(".bitly").on("keyup", function () { | |
var btnOnkeyup = $(this); | |
var url_val = btnOnkeyup.val(); | |
if (url_val.length < SHORTEN_URL_LENGTH) { | |
return; | |
} | |
// 結果を表示 | |
convertBitly(url_val, 'bitly.com').done(function (d) { | |
if (d.data.url) { | |
btnOnkeyup.val(d.data.url); | |
} | |
}); | |
}); | |
} | |
// Bitly APIにリクエスト | |
function convertBitly(url, domain) { | |
var encUrl = encodeURIComponent(url); | |
console.log('encUrl = ' + encUrl); | |
var bitly = "https://api-ssl.bitly.com/v3/shorten?access_token=[bitly Generic Access Token]&longUrl=" + encUrl + "&domain=" + domain; | |
var d = new $.Deferred(); | |
$.ajax({ | |
type: "get", | |
url: bitly, | |
dataType: "jsonp", | |
processData: false, | |
contentType: false, | |
success: d.resolve, | |
error: d.reject | |
}); | |
return d.promise(); | |
} | |
return { | |
init: function () { | |
getUrl(); | |
} | |
}; | |
} ()); | |
$(document).ready(function () { | |
generateUrl.init(); | |
}); |
以上
inputボックスにURL打ち込むと自動URL短縮化されるjs
https://kenzo0107.github.io/2016/03/09/2016-03-10-auto-shorten-url-js/