Webサイト運営において、外部リンクの取り扱いはSEOやセキュリティの観点から非常に重要です。特に以下のような対応が推奨されます:
- 外部リンクには
rel="noopener nofollow"
を付加(セキュリティ & SEO対策) - 信頼できないリンクは新しいタブで開かせる(ユーザーの離脱防止)
この記事では、**jQuery と Vanilla JS(純粋なJavaScript)**の両方で「外部リンクの制御」を自動化する方法をご紹介します。
✅ 対象とする条件
- 外部リンク(
http://
やhttps://
で始まり、かつ自サイト以外のドメイン) - ただし、以下はいずれも「信頼済み」として除外します:
analyzegear.co.jp
ドメイン.trusted-link
クラスが付いているリンク
🧩 jQueryでの実装方法
🔸スクリプト例
$(function() {
const trustedDomains = ["analyzegear.co.jp"];
$("a")
.filter('[href^="http"], [href^="//"]')
.not('[href*="'+window.location.host+'"]')
.each(function() {
const href = $(this).attr("href");
const isTrustedDomain = trustedDomains.some(domain => href.includes(domain));
// relは必ず付加
$(this).attr("rel", "noopener nofollow");
// target="_blank" を信頼リンク以外に付与
if (!$(this).hasClass("trusted-link") && !isTrustedDomain) {
$(this).attr("target", "_blank");
}
});
});
🧩 Vanilla JSでの実装方法
document.addEventListener("DOMContentLoaded", function () {
const links = document.querySelectorAll('a[href^="http"], a[href^="//"]');
const currentHost = window.location.host;
const trustedDomains = ["analyzegear.co.jp"];
links.forEach(function (link) {
const href = link.getAttribute("href");
// 自ドメインを含む場合は除外
if (href.includes(currentHost)) return;
// rel属性を付加
link.setAttribute("rel", "noopener nofollow");
// trusted-link クラス または 信頼ドメイン以外の場合は target=_blank
const isTrustedClass = link.classList.contains("trusted-link");
const isTrustedDomain = trustedDomains.some(domain => href.includes(domain));
if (!isTrustedClass && !isTrustedDomain) {
link.setAttribute("target", "_blank");
}
});
});
🎨 任意:CSSで信頼リンクを視覚的に装飾する
a.trusted-link::after {
content: " 🔒";
color: #4CAF50;
font-size: 0.9em;
}
.trusted-link
に対して視覚的に「信頼済みリンク」であることを示すマークを表示することができます(任意)。
✅ 想定される活用例
リンク | 結果 |
---|---|
<a href="https://google.com"> | _blank + rel=... 付加 |
<a href="https://analyzegear.co.jp"> | relのみ、_blank は付加しない |
<a href="/about"> | 処理されない(内部リンク) |
<a href="https://foo.com" class="trusted-link"> | relのみ、_blank なし |
📝 まとめ
処理内容 | 対象 |
---|---|
rel="noopener nofollow" | 全ての外部リンクに強制的に付加 |
target="_blank" | .trusted-link か analyzegear.co.jp 以外の外部リンク |
.trusted-link クラス | 手動で信頼リンクをマークできる |
analyzegear.co.jp ドメイン | 自動的に信頼リンクとして扱う |
💬 補足
rel="noopener"
はセキュリティ対策(ウィンドウ操作やフィッシングの防止)として非常に重要です。nofollow
はSEO的に外部リンクの評価をパスしないための指定です。target="_blank"
を付けることでユーザーのページ離脱を防げますが、信頼されたリンクには不要という判断も合理的です。
コメント