本文分享三段實作「加入收藏」與「設為首頁」功能的 JavaScript 程式碼,供需要的朋友參考。
原理:先取出 navigator.userAgent 並轉小寫,判斷目前是哪個瀏覽器,再決定要呼叫哪個收藏 API。若都不支援,就提示使用者按 Ctrl+D 手動收藏。
function addFavorite2() {
var url = window.location;
var title = document.title;
var ua = navigator.userAgent.toLowerCase();
if (ua.indexOf("360se") > -1) {
alert("由於360浏覽器功能限制,請按 Ctrl+D 手動收藏!");
} else if (ua.indexOf("msie 8") > -1) {
window.external.AddToFavoritesBar(url, title); //IE8
} else if (document.all) {
try{
window.external.addFavorite(url, title);
}catch(e){
alert('您的浏覽器不支持,請按 Ctrl+D 手動收藏!');
}
} else if (window.sidebar) {
window.sidebar.addPanel(title, url, "");
} else {
alert('您的浏覽器不支持,請按 Ctrl+D 手動收藏!');
}
}
把這段存成 js 檔引入,然後在要放按鈕的位置寫上:
<a href="#" onclick="javascript:addFavorite2()">加入收藏</a>
// JavaScript Document
// 加入收藏 <a onclick="AddFavorite(window.location,document.title)">加入收藏</a>
function AddFavorite(sURL, sTitle) {
try {
window.external.addFavorite(sURL, sTitle);
} catch (e) {
try {
window.sidebar.addPanel(sTitle, sURL, "");
} catch (e) {
alert("加入收藏失敗,請使用Ctrl+D進行添加");
}
}
}
//設為首頁 <a onclick="SetHome(this,window.location)">設為首頁</a>
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);
}
}
}
使用方式:
<a href="#" onclick="SetHome(this,window.location)" >設為首頁</a> <a href="#" onclick="AddFavorite(window.location,document.title)" >收藏本站</a>
許多網站為了留住訪客都會放「設為首頁」、「加入收藏」按鈕,精簡寫法如下:
<script>
function addfavorite() {
if (document.all) {
window.external.addFavorite('https://www.jb51.net','');
} else if (window.sidebar) {
window.sidebar.addPanel('', 'https://www.jb51.net', "");
}
}
</script>
<body>
<a href="#" onclick="addfavorite()">加入收藏!</a>
測試結果:該程式碼對 IE6+ 與 Firefox 有效,Chrome 無效。
必須說明的是,上述所有程式碼在當今的瀏覽器中都不再可用。出於安全與垃圾內容防制的考量,瀏覽器已全面移除讓網頁腳本呼叫「加入書籤」與「設為首頁」的能力——否則任何網站都能擅自改寫使用者的首頁設定。document.all 這個判斷條件在現代瀏覽器中也有專門為了相容而設計的怪異行為,不能當作 IE 的判準。
現階段可行的替代方案是:在頁面上清楚提示使用者按 Ctrl+D(Mac 為 Cmd+D)收藏,或提供一顆真正的 RSS/網路應用程式安裝入口。若產品是 PWA,則可引導使用者使用瀏覽器選單中的「安裝」功能。硬要用程式去呼叫這些已廢棄的 API,只會在 console 留下錯誤而毫無效果。
以上就是這三種寫法的整理,希望對你有所幫助。