「設為首頁」和「加入收藏」是許多網站常見的功能按鈕,但在 IE、Firefox、Chrome 等主流瀏覽器上要做到完全兼容並不容易。經過多次嘗試,我整理出一套相對通用的解決方案。若想把問題徹底解決,最理想的方式其實是像大型網站那樣,另外建立一個「添加為首頁」的操作步驟說明頁。
<script type="text/javascript">
// 設置為主頁
function SetHome(obj, vrl){
try{
obj.style.behavior='url(#default#homepage)';
obj.setHomePage(vrl);
} catch(e){
if(window.netscape) {
try {
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
} catch (e) {
alert("此操作被浏覽器拒絕!\n請在浏覽器地址欄輸入about:config並回車\n然後將 [signed.applets.codebase_principal_support]的值設置為true");
}
var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
prefs.setCharPref('browser.startup.homepage', vrl);
}else{
alert("您的浏覽器不支持,請按照下面步驟操作:1.打開浏覽器設置。2.點擊設置網頁。3.輸入:"+vrl+"點擊確定。");
}
}
}
// 加入收藏 兼容360和IE6
function shoucang(sTitle, sURL){
try {
window.external.addFavorite(sURL, sTitle);
} catch (e) {
try {
window.sidebar.addPanel(sTitle, sURL, "");
} catch (e) {
alert("加入收藏失敗,請使用Ctrl+D進行添加");
}
}
}
</script>
<li class="fore1"><a href="javascript:void(0)" onclick="SetHome(this,window.location)">設為首頁</a></li>
<li class="ge">|</li>
<li class="fore2"><a href="javascript:void(0)" onclick="shoucang(document.title,window.location)">加入收藏</a></li>
以下是一些更基礎的 HTML 寫法,主要供初學者參考。請注意:這類代碼通常僅兼容 IE 瀏覽器。
加入收藏(滑鼠移過即提示):
<a onmouseover="window.external.addFavorite('https://www.baidu.com','百度')" target=_self href= >加入收藏</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/');">
頁面打開時自動彈出詢問視窗,將以下代碼放在 <head></head> 之間:
<script language="javascript">
function myhomepage(){
this.homepage.style.behavior='url(#default#homepage)';
this.homepage.sethomepage('https://www.baidu.com');
}
</script>
<p align="center"><a href="https://www.baidu.com/" name="homepage" onclick="myhomepage();"></a>
再將 onload="myhomepage();" 加入 <body> 標籤內即可。
滑鼠指向時提示設為首頁:
<A href="https://www.baidu.com/" onmouseover="this.style.behavior='url(#default#homepage)';this.setHomePage('https://www.baidu.com/');" target="_blank">設為首頁</A>
關閉當前視窗:
<a href="/" onclick="javascript:window.close(); return false;">關閉窗口</a>
連結到電子郵箱:
<a href="mailto:baidujishubu@163.com">電子信箱</a>