[JavaScript] 現在アクセス中のドメインによって a href の URL を書き換える
- 2017 12/26
- カテゴリー : 未分類
- JavaScript
- コメントを書く
現在アクセス中のドメインによって a href の URL を書き換える JavaScript のサンプルコードをご紹介します。
現在アクセス中のドメインは document.domain で取得できるので、これを元に特定のドメインのときだけ href を書き換えてます。
HTML
<a class="js-button" href="https://production.example.com/target_site" target="_blank" rel="noopener noreferrer"> <img src="button.png" alt="Sample Button"> </a> |
JavaScript
var button = document.getElementsByClassName('js-button');
if (button !== null) {
var href = button[0].getAttribute('href');
var domain = document.domain;
// 現在アクセス中のドメインが test.example.com のときだけ URL 更新
if (domain === 'test.example.com') {
href = 'https://another.example.com/target_site';
}
}
以上、クライアントサイドで test サイトのときだけ URL を書き換えたい現場からお送りしました。