您的位置:首页 > Web前端 > JavaScript

设为首页与加入收藏的JS代码(多浏览器支持)

2012-12-11 09:05 465 查看
先分享两个设置首页的js代码(不符合标准不谈兼容性):

两种方法将当前页设为你浏览器的主页,一种是将你正在浏览的网页设为首页;另一种是将指定网址设为首页,至于你用哪一种,看你的需要了,各有各适用的场合。

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

<title>设为首页的JS代码</title>

</head>

<body>

<p>方法一:<span onclick="var strHref=window.location.href;this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.jb51.net');" style="CURSOR: hand">点此

设为首页</a></span></p>

<p>

方法二:<a title="设为首页" onclick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.jb51.net');" href="javascript:;">设为首页</a> </p>

</body>

</html>

下面的代码兼容性好符合标准,但ie7无法支持加入收藏,不过已经算是比较好的代码了

<!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=gb2312" />

<title>设为首页与添加收藏夹代码【兼容多浏览器】</title>

<script language="javascript">

function addBookmark(title,url) {

if (window.sidebar) {

window.sidebar.addPanel(title, url,"");

} else if( document.all ) {

window.external.AddFavorite( url, title);

} else if( window.opera && window.print ) {

return true;

}

}

function setHome(url)

{

if (document.all){

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" );

}

}

if(window.confirm("你确定要设置"+url+"为首页吗?")==1){

var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);

prefs.setCharPref('browser.startup.homepage',url);

}

}

}

</script>

</head>

<body>

<a href="javascript:void(null)" onClick="setHome('http://www.jb51.net');">设为首页</a> - <a href="javascript:addBookmark('脚本之家','http://www.jb51.net')">加入收藏</a>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: