Chrome 和 Safari 通过 JavaScript 添加书签

发布时间:  最終更新日:2012/04/08   QQ/微信:1176113114

估计很多朋友都遇到过这个问题,Webkit 核心的浏览器(Chrome 和 Safari)添加浏览器书签的方法,但是不一定都解决掉了,今天上网找资料的时候发现了一个通过模拟快捷键在 Chrome 中添加书签的方法,经过测试在 Chrome 和 Safari 中都可正常运行,源码摘抄如下:

function hotKeys() {
var ua = navigator.userAgent.toLowerCase();
var str = '';
var isWebkit = (ua.indexOf('webkit') != - 1);
var isMac = (ua.indexOf('mac') != - 1);

if (ua.indexOf('konqueror') != - 1) {
str = 'CTRL + B'; // Konqueror
} else if (window.home || isWebkit || isIEmac || isMac) {
str = (isMac ? 'Command/Cmd' : 'CTRL') + ' + D'; // Netscape, Safari, iCab, IE5/Mac
}
return ((str) ? 'Press ' + str + ' to bookmark this page.' : str);
}

如果要兼容其他浏览器的话,完整的代码就是:
BookmarkApp = function () {
var isIEmac = false; /*@cc_on @if(@_jscript&&!(@_win32||@_win16)&&
(@_jscript_version<5.5)) isIEmac=true; @end @*/
var isMSIE = (-[1,]) ? false : true;
var cjTitle = "Welcome to CodeCTO.com";
var cjHref = location.href;

function hotKeys() {
var ua = navigator.userAgent.toLowerCase();
var str = '';
var isWebkit = (ua.indexOf('webkit') != - 1);
var isMac = (ua.indexOf('mac') != - 1);

if (ua.indexOf('konqueror') != - 1) {
str = 'CTRL + B'; // Konqueror
} else if (window.home || isWebkit || isIEmac || isMac) {
str = (isMac ? 'Command/Cmd' : 'CTRL') + ' + D'; // Netscape, Safari, iCab, IE5/Mac
}
return ((str) ? 'Press ' + str + ' to bookmark this page.' : str);
}

function isIE8() {
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})");
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1);
}
}
if (rv > - 1) {
if (rv >= 8.0) {
return true;
}
}
return false;
}

function addBookmark(a) {
try {
if (typeof a == "object" && a.tagName.toLowerCase() == "a") {
a.style.cursor = 'pointer';
if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
window.sidebar.addPanel(cjTitle, cjHref, ""); // Gecko
return false;
} else if (isMSIE && typeof window.external == "object") {
if (isIE8()) {
window.external.AddToFavoritesBar(cjHref, cjTitle); // IE 8
} else {
window.external.AddFavorite(cjHref, cjTitle); // IE <=7
}
return false;
} else if (window.opera) {
a.href = cjHref;
a.title = cjTitle;
a.rel = 'sidebar'; // Opera 7+
return true;
} else {
alert(hotKeys());
}
} else {
throw "Error occured.rnNote, only A tagname is allowed!";
}
} catch (err) {
alert(err);
}

}

return {
addBookmark : addBookmark
}
}();

来源:CodeCTO

打赏

推广:ChinaApp营销论坛——苹果AppStore搜索广告Search Ads交流区

感谢分享给更多身边的朋友

回顶部 ↑