Welcome 微信登录

首页 / 脚本样式 / JavaScript / javascript实现网站加入收藏功能

本文为大家分享了三段javascript实现网站加入收藏功能的代码,具体内容如下
第一种情况:可兼容所有浏览器的加入收藏代码原理:根据获取用户navigator.userAgent.toLowerCase()信息来判断浏览器,根据浏览器是否支持加入收藏js命令,如果可以自动收藏否则就提示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>
第二种情况:js代码实现设为首页并加入收藏
// 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("此操作被浏览器拒绝!
请在浏览器地址栏输入“about:config”并回车
然后将 [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>
第三种情况:js添加收藏代码
很多网站为了聚集用户和维持流量都有"设为首页","添加收藏"等按钮,js添加收藏代码如下:
<script>function addfavorite(){if (document.all){ window.external.addFavorite("http://www.jb51.net","脚本之家");}else if (window.sidebar){ window.sidebar.addPanel("脚本之家", "http://www.jb51.net", "");}} </script><body><a href="#" onclick="addfavorite()">加入收藏!</a>
结果测试:该代码对IE6+,和FireFox均有效,Chrome无效!
以上就是js代码实现设为首页并加入收藏功能,希望大家喜欢。