May
23
2013
兼容IE和firefox的设置首页和加入收藏的JavaScript代码
作者:
绝缘体.. 发布:
2013-05-23 13:50 分类:
未分类 阅读:
抢沙发
如下分别是设为首页和加入收藏的代码效果:
<a href="#" onclick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://phpernote.com')">设为首页</a>
<a href="javascript:window.external.AddFavorite('http://phpernote.com','PHP程序员的笔记')">添加收藏</a>
注意:以上代码仅适合IE内核的浏览器,现特将兼容IE和火狐浏览器的代码贴在下面:
//加入收藏
function AddFavorite(URL,Title){
URL=URL||window.location.href;
Title=Title||document.title;
try{
window.external.addFavorite(URL,Title);
}catch(e){
try{
window.sidebar.addPanel(Title,URL,"");
}catch(e){
alert("加入收藏失败,请使用Ctrl+D进行添加");
}
}
}
//设为首页
function setHomepage(URL){
URL=URL||window.location.href;
if(document.all){//IE类浏览器
document.body.style.behavior='url(#default#homepage)';
document.body.setHomePage(URL);
}else if(window.sidebar){//火狐类浏览器
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',URL);
}
}
以上函数的在页面中的调用方式如下:
<a href ="javascript:void(0)" onclick ="setHomepage()">设为首页</a>
<a href="javascript:void(0)" onclick ="AddFavorite()">加入收藏</a>
<a href="javascript:void(0)" onclick ="AddFavorite('http://www.phpernote.com/','php程序员教程网')">加入收藏</a>
微信扫一扫,打赏作者吧~