[2016/06/08追加]
動的にボタンを追加するAPIがあるみたいですね。
dev.twitter.com
Twitterボタンには以下の属性が設定可能です。
- type
- ボタンのタイプ
-
- size
- ボタンのサイズ
- lang
- ボタン表示の言語設定
- text
- ツイート内容
- url
- 添付するURL
- hashtags
- ハッシュタグ
- id
- ボタン(iframe)のid
- time
- ボタン生成時刻
- original_referer
- ボタンが配置されたページのURL
- dnt
- Twitterによるカスタマイズのオプトアウトのオンオフ
ウェブアプリでゲームを作って、ゲームの成績をツイートするような場合には上記のtextに結果を埋め込みたいです。
ボタンに変換されるアンカーaを動的に生成、追加して、twttr.
widget.load()を実行すればいいのですが、元々ボタンが設置されている場合、削除してload()を実行するのは、それなりにオーバーヘッドがあるかなと思いました。
なので、iframeのsrcを直接変更してみたのですが、ボタンが更新されない。調べたところ、上記のパラメータがsrcのハッシュ部分に埋め込まれていて、ハッシュだけの更新の場合、iframeは再読み込みを実行しないからでした。
原因がわかれば対策は簡単で、キャッシュを外すよくあるテクニックで、ダミーのタイムスタンプを付けることで解決しました。
以下、コードスニペット(CoffeeScript, jQuery使用)です。
parseTwitterButtonSrc = (url) ->
match = url.match /(.*)#(.*)/
unless match?
return null
result =
page: match[1]
params: {}
for eq in match[2].split '&'
match = eq.match /(.*)=(.*)/
if match?
result.params[decodeURIComponent match[1]] = decodeURIComponent match[2]
result
composeTwitterButtonSrc = (obj, timestamp = false) ->
head = obj.page
if timestamp
head += "?dummy=#{Date.now()}"
head + '#' + (encodeURIComponent(k) + '=' + encodeURIComponent(v) for k, v of obj.params).join '&'
updateButtonText = ($target, text) ->
parsed = parseTwitterButtonSrc $target.attr 'src'
parsed.params.text = text
$target.attr 'src', composeTwitterButtonSrc parsed, true
return