设为首页和加入收藏一直是很多网站提供的小功能,今天特别研究了一下,传统的设为首页的代码如下:
<a href="#setHomePage" onclick="this.style.behavior='url(#default#homepage)';this.setHomePag('http://wangye.org/');return false;">设为首页</a>
似乎很长的一段时间上面这段代码一直工作得很好,但是随着其他非IE内核的浏览器异军突起,比如FF(FireFox),很多童鞋发现这样的代码已经失去了原有的作用,所以兼容的代码就显得非常的重要了。
对于FireFox来说,安全设置成为阻碍设为首页代码的关键因素,不过我们不得不承认这些安全设置为我们安全浏览进行保驾护航,不过如果要在FF上设为首页,那么我们需要开启UniversalXPConnect权限,当然在启用这个权限的同时浏览器会提示安全消息要求用户授权,若用户不予以授权的话,下面的代码将会因为权限问题而得不到执行。(远程调试时如果不做相关设置将不会出现授权对话框,直接默认是拒绝授权)相关要求授权的对话框如下:

所以如果检测到用户没有授权,应该给出相关提示,详细的代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| if (window.sidebar) {
if (window.netscape) {
try {
netscape.security.PrivilegeManager
.enablePrivilege("UniversalXPConnect");
} catch(e) {
// this action was aviod by your browser,
// if you want to enable,please enter
// about:config in your address line,
// and change the value of
// signed.applets.codebase_principal_support to true
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);
} |
if (window.sidebar) {
if (window.netscape) {
try {
netscape.security.PrivilegeManager
.enablePrivilege("UniversalXPConnect");
} catch(e) {
// this action was aviod by your browser,
// if you want to enable,please enter
// about:config in your address line,
// and change the value of
// signed.applets.codebase_principal_support to true
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);
}
if (window.sidebar)是判断FF的一种方法,就像判断IE用if (document.all)一样,结合一下,兼容IE和FF的设为首页的代码如下:
继续阅读“兼容IE和FireFox设为首页和加入收藏的JavaScript代码”