本文整理多種「加入收藏」與「設為首頁」的 JavaScript 語法,並附上最基本的 HTML 寫法,供初學者參考。請注意:以下語法主要相容 Internet Explorer 瀏覽器。
最基礎的寫法是利用 window.external.AddFavorite,只要把網址與站名換成自己的即可:
<a href="javascript:window.external.AddFavorite('https://www.baidu.com','百度')">加入收藏</a>若希望滑鼠移過時就提示是否加入收藏,可改用 onmouseover 觸發:
<a onmouseover="window.external.addFavorite('https://www.baidu.com','百度')"
href="https://www.baidu.com/">加入收藏</a>設為首頁主要透過 behavior:url(#default#homepage) 搭配 setHomePage() 完成。
圖片連結型:
<a style="cursor:hand" onclick="this.style.behavior='url(#default#homepage)';
this.setHomePage('https://www.baidu.com/');">
<img width="16" height="16" border="0" src="images/house.png">
<u>Set as Home Page</u></a>文字型:
<a onclick="this.style.behavior='url(#default#homepage)';
this.setHomePage('https://www.baidu.com/');" href="#">設為首頁</a>按鈕型:
<input type="button" value="設為首頁"
onclick="this.style.behavior='url(#default#homepage)';
this.setHomePage('https://www.baidu.com/');">離開頁面時自動提示設為首頁:
<body onunload="BASEBody.style.behavior='url(#default#homepage)';
if(!(BASEBody.isHomePage('https://www.baidu.com/')))
BASEBody.setHomePage('https://www.baidu.com/');">開啟頁面時自動彈出視窗詢問:把函式放在 head 之間,並在 body 的 onload 觸發:
<script language="javascript">
function myhomepage(){
this.homepage.style.behavior='url(#default#homepage)';
this.homepage.sethomepage('https://www.baidu.com');
}
</script>
<body onload="myhomepage();">滑鼠指向時提示設為首頁:
<a href="https://www.baidu.com/"
onmouseover="this.style.behavior='url(#default#homepage)';
this.setHomePage('https://www.baidu.com/');" target="_blank">設為首頁</a>為文字建立連結後,在 onclick 事件中呼叫 window.close() 即可:
<a href="/" onclick="javascript:window.close(); return false;">關閉視窗</a>
提醒您,由於安全性考量,現代瀏覽器多半已限制這類自動設定首頁或關閉視窗的行為,實際部署時應以主流瀏覽器的現行政策為準。