LoginSignup
3
0

More than 1 year has passed since last update.

SNSシェアボタンにUTMパラメーターを付与する方法

Last updated at Posted at 2021-06-01

概要

行動分析のためのGA4のUTMパラメーターをTwitterシェアのURLに追加したところ、
ツイート内に期待していたURLが出てこなかったため一工夫した話

期待していたURL

https://mysite.com/?utm_source=hogehoge&utm_medium=fugafuga&utm_campaign=piyopiyo

ツイート内に含まれていたURL

https://mysite.com/?utm_source=hogehoge

&で区切られてutm_medium以降は不要なパラメーターとして捨てられてしまっています。
上記を見て、雑な実装として自分でエスケープ(& => %26)してしまえばいいやと思って書き直したのが下記です。一応、動作するはずです。

?utm_source=hogehoge%26utm_medium=fugafuga%26utm_campaign=piyopiyo

なんだか不格好ですのでちゃんと実装していきます。

実装内容

// hogehoge fugafuga piyopiyoの箇所は必要に応じて関数等で動的に実装
const utmSource = 'utm_source=' + 'hogehoge'
const utmMedium = 'utm_medium=' + 'fugafuga'
const utmCampaign = 'utm_campaign=' + 'piyopiyo'
const utmParams = encodeURIComponent('?' + utmSource +'&' + utmMedium + '&' + utmCampaign)
const url = window.location.href                 // シェアボタンはシェアするページに配置する想定
const text = 'ツイート本文 hogefugapiyo'            // 適当なツイート本文

const tweetUrl = 'https://twitter.com/intent/tweet?url=' + url + utmParams + '&text=' + text

window.open(tweetUrl);

今回はTwitterのみの記載となりますが、他のSNSシェアボタンでも同様の処理が必要となるかと思います。

その他

エンコードの関数としてencodeURI()があるが、こちらは&をエスケープしないため、encodeURIComponent()を利用する必要がある。
詳細は下記をご参照ください。

3
0
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
0