| 屬性值 | 作用 | 必要性 |
noopener | 新頁面 window.opener 為 null,防止反向訪問/重定向攻擊 | 必須 |
noreferrer | 不發送 Referer 頭,保護隱私,兼容舊瀏覽器無 noopener 支持 | 推薦 |
現代瀏覽器 target="_blank" 隱含 noopener 行為,但顯式聲明更安全、語義更清晰。
進階:精確識別「外部」鏈接
單純匹配 https:// 會誤判同域絕對路徑鏈接。正確做法:比較 hostname。
$(function() {
var currentHost = window.location.hostname; // 如 "example.com"
$("a[href^='https://'], a[href^='https://']").each(function() {
var $link = $(this);
var href = $link.attr("href");
try {
// 使用 URL API 解析(現代瀏覽器)
var url = new URL(href, window.location.href);
if (url.hostname !== currentHost) {
// 外部鏈接
$link.attr("target", "_blank")
.attr("rel", "noopener noreferrer")
.addClass("external-link"); // 可選:添加樣式類
}
} catch (e) {
// 無效 URL,跳過
}
});
});
CSS 視覺提示:外鏈圖標
.external-link::after {
content: " 🔗"; /* 或使用圖標字體 */
font-size: 0.8em;
margin-left: 2px;
vertical-align: super;
opacity: 0.7;
}
.external-link:hover::after {
opacity: 1;
}
完整生產級實現
/**
* 外部鏈接自動處理插件
* @param {Object} options
* @property {string} selector - 鏈接選擇器,默認 'a[href^="http"]'
* @property {boolean} addIcon - 是否添加外鏈圖標
* @property {string} relValue - rel 屬性值,默認 'noopener noreferrer'
* @property {Function} filter - 自定義過濾函數 (href, currentHost) => boolean
*/
$.fn.externalLinks = function(options) {
var opts = $.extend({
selector: 'a[href^="https://"], a[href^="https://"]',
addIcon: true,
relValue: "noopener noreferrer",
filter: null
}, options);
var currentHost = window.location.hostname;
return this.find(opts.selector).addBack(opts.selector).each(function() {
var $link = $(this);
var href = $link.attr("href");
if (!href) return;
try {
var url = new URL(href, window.location.href);
// 默認邏輯:不同 hostname 為外鏈
var isExternal = url.hostname !== currentHost;
// 自定義過濾器
if (opts.filter) {
isExternal = opts.filter(href, currentHost, url);
}
if (isExternal) {
$link.attr("target", "_blank")
.attr("rel", opts.relValue);
if (opts.addIcon) $link.addClass("external-link");
}
} catch (e) {
// 忽略無效 URL
}
});
};
// 使用
$(document).ready(function() {
$(document).externalLinks({
addIcon: true,
filter: function(href, host, urlObj) {
// 例外:子域視為內部
return urlObj.hostname !== host && !urlObj.hostname.endsWith("." + host);
}
});
});
服務端渲染(SSR)視角:更優的方案
在模板引擎中直接輸出屬性,避免 JS 執行延遲、SEO 問題、無 JS 環境失效:
{{#each links}}
<a href="{{url}}"
{{#if isExternal}}target="_blank" rel="noopener noreferrer" class="external-link"{{/if}}
>{{text}}</a>
{{/each}}
總結
外部鏈接新窗口打開,靜態設置 target="_blank" + rel="noopener noreferrer" 是標準做法。jQuery 可用於客戶端動態修補,但服務端渲染更優。關鍵點:
- 準確識別外鏈(比較 hostname,而非單純匹配 https://)
- 必須添加
rel="noopener noreferrer" 防安全風險
- 提供視覺提示(圖標/樣式)讓用戶預知行為
- 考慮 SSR、CSP、無障礙等綜合因素
copyright ©
萬盛學電腦網 all rights reserved