在早期的 ASP 開發中,「加入我的最愛」是常見的使用者互動功能。雖然現代瀏覽器已內建書籤管理,但理解其實作邏輯仍有助於掌握伺服器端與客戶端的協作。本文將拆解一段經典的 ASP 程式碼,示範如何取得訪客 IP、當前網址,並呼叫瀏覽器的 window.external.AddFavorite 方法完成收藏。
<%
Function GetClientIP()
If Request.ServerVariables("HTTP_X_FORWARDED_FOR") = "" Then
GetClientIP = Request.ServerVariables("REMOTE_ADDR")
Else
GetClientIP = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
End If
End Function
Response.Write "您的 IP:" & GetClientIP()
%>
說明: 透過 HTTP_X_FORWARDED_FOR 判斷是否經由代理伺服器,若無則直接讀取 REMOTE_ADDR。此函式可獨立作為工具函式重複使用。
<script>
var hostname = location.hostname; // 當前域名
var currentUrl = location.href; // 完整 URL
</script>
這兩個變數將在「加入收藏」連結中被引用。
<a href="#" onclick="this.style.behavior='url(#default#homepage)';
window.external.AddFavorite(currentUrl, 'www.example.com')">
加入收藏
</a>
behavior='url(#default#homepage)':啟用 IE 專屬的首頁行為,為 AddFavorite 做準備。window.external.AddFavorite(url, title):IE 專用方法,第一參數為網址,第二為書籤標題。AddFavorite 僅 IE 支援,Chrome、Firefox、Edge 等現代瀏覽器均已移除或封鎖此 API。location.href 回傳的也是 HTTPS 連結,避免混合內容警告。<%@ Language=VBScript %>
<html>
<head><title>加入我的最愛示範</title></head>
<body>
<%
Function GetClientIP()
If Request.ServerVariables("HTTP_X_FORWARDED_FOR") = "" Then
GetClientIP = Request.ServerVariables("REMOTE_ADDR")
Else
GetClientIP = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
End If
End Function
%>
<p>您的 IP 位址:<%=GetClientIP()%></p>
<script>
var currentUrl = location.href;
var siteTitle = document.title;
</script>
<a href="#" onclick="window.external.AddFavorite(currentUrl, siteTitle); return false;">
★ 加入我的最愛
</a>
<p class="note">※ 若您使用非 IE 瀏覽器,請手動按 Ctrl+D 加入書籤。</p>
</body>
</html>