兼容Ie、Chrome、FF的设为首页和收藏本站js代码

代码2015-03-021,921 人已阅来源:网络

这是一段很牛B的代码,兼容性超好。现在很多大型网站的设为首页和加入收藏代码在Chrome和FF里根本毫无反应,哥笑而不语…

这里虽然说是兼容的意思,但是有些浏览器自身就是不支持用js来把页面设为首页,只能加入收藏夹。设为首页只能让用户手动去在浏览器或者按键去设置这些功能,这里说的兼容是指当浏览器有这个设置的时候js会有提示。

这段代码几乎兼容所有浏览器的….这是我自己常用的设为首页加入收藏代码,具体也可以在小站的logo右边五角形试验一下…也可以在以下运行中测试

兼容Ie、Chrome、FF的设为首页和收藏本站js代码

客官请看Demo

运行代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>兼容ie,chrome,ff的设为首页和收藏本站js代码  web前端资源网 | www.tonjay.com</title>
</head>
<body>
<script type="text/javascript">
function AddFavorite(sURL, sTitle) {
    try { //IE
        window.external.addFavorite(sURL, sTitle);
    } catch (e) {
        try { //Firefox
            window.sidebar.addPanel(sTitle, sURL, "");
        } catch (e) {
   try{//Chrome无法自动收藏,用创建快应用程序的捷方式来替代。web前端资源网 www.tonjay.com
    createShortcut();
   } catch(e){
    alert("请按Ctrl+D之后按“确定”完成收藏!");
   }
        }
    }
}
function setHomepage(pageURL) {
    if (document.all) {
        document.body.style.behavior='url(#default#homepage)';
        document.body.setHomePage(pageURL);
    }
    else {
            try { //IE
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            } catch (e) {
    try{ //Firefox
     var prefs = Components.classes['@mozilla.org/preferences-service;1']
.getService(Components. interfaces.nsIPrefBranch);
     prefs.setCharPref('browser.startup.homepage',pageURL);
    } catch(e) {
                alert( "您的浏览器不支持该操作,请使用浏览器菜单手动设置." );
    }
            }
    }
}
</script>
<style>
p a{ margin:0 20px; text-decoration:none; color:#666;}
p a:hover{ color:#000;}
</style>
<p align="center">
<a href="javascript:void(0);" title="加入收藏"  onclick="setHomepage('https://aihongxin.com');">设为首页</a>
<a href="javascript:void(0)" title="加入收藏" onclick="javascript:AddFavorite('https://aihongxin.com','web前端资源网');">加入收藏</a></p>
</body>
</html>