从 JavaScript 添加到浏览器收藏夹/书签但适用于所有浏览器(我的浏览器在 Chrome 中不起作用)?

发布于 2024-07-24 05:41:28 字数 524 浏览 7 评论 0原文

任何人都可以帮忙,我正在使用以下方法向 IE 和 Firefox 添加书签,但它在 Chrome 中不起作用,而且我也没有收到错误消息说“不支持”。

任何人都知道支持所有浏览器的好脚本或者至少回来告诉我它不受支持,我可以访问 jQuery - 也许有某种方法可以检测

我当前正在使用的浏览器,它适用于 IE 和 Firefox,但不适用于 chrome

if (window.sidebar) { // Mozilla Firefox
    window.sidebar.addPanel(name, url, "");
}
else if (window.external) { // IE
    window.external.AddFavorite(url, name);
}
else if (window.opera && window.print) {
    window.external.AddFavorite(url, name);
}
else {
    alert('not supported');
}

Can anyone help, I am using the following for adding a bookmark to IE and Firefox but its not working in Chrome and I don't get my error msg saying "not supported" either..

Anybody know of a good script to support ALL browsers or at least to come back and tell me its not supported, I have access to jQuery - maybe there is some way to detect the browser

I am currently using this and it works for IE and Firefox but not chrome

if (window.sidebar) { // Mozilla Firefox
    window.sidebar.addPanel(name, url, "");
}
else if (window.external) { // IE
    window.external.AddFavorite(url, name);
}
else if (window.opera && window.print) {
    window.external.AddFavorite(url, name);
}
else {
    alert('not supported');
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

舟遥客 2024-07-31 05:41:28

抱歉,没有跨浏览器的方法可以做到这一点。 你的 FF 示例也被破坏了:它不会创建常规书签,而是创建一个在侧边栏中打开的书签。 您必须使用书签服务来创建实际的书签,但这'由于安全限制,将会失败。

Sorry, but there's no cross-browser way to do this. Your FF example is broken as well: It won't create a regular bookmark, but a bookmark set to be opened in the sidebar. You'd have to use the bookmark-service to create an actual bookmark, but this'll fail due to security restrictions.

七月上 2024-07-31 05:41:28

发现后——就像爱迪生一样! - 很多方法都行不通,我最终遇到了 此页面显示通过 JS 添加书签在 Chrome 中已被明确禁用。 不幸的是它没有解释原因。

更新:另一位 SO 用户要求我扩展此答案...

此功能的链接和按钮都有一个与之关联的 class="addbookmark" 。 当用户代理是 Chrome 时,我使用一些 jQuery 来禁用链接并解释原因:

<script type="text/javascript" src="/scripts/jquery-1.4.2.min.js"></script> 
<script type="text/javascript" src="/scripts/bookmark.js"></script> 
<script> 
    title='A Label for this Bookmark, ie title of this page'; // for example, not really generated this way... 

    $jQuery(document).ready(function(){ 
        // chrome does not permit addToFavorites() function by design 
        if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { 
            $('.addbookmark').attr({ 
                title: 'This function is not available in Google Chrome. Click the star symbol at the end of the address-bar or hit Ctrl-D to create a bookmark.', 
                href: 'javascript:return false' 
            }) 
            .css({opacity: .25});       // dim the button/link 
        } 
    }); 
</script> 

然后在页面的其他地方:

 <td rowspan="2" class="noprint" style="width:24px;"> 
     <a class="addbookmark" title="Save a Bookmark for this page" 
        href="javascript:addToFavorites(location.href,title)"> 
        <img style="width:24px; height:24px; padding-top:2px;" src="/images/bookmark.gif"></a> 
 </td> 

... 这绝不是完美的,但似乎一个人的选择相当有限。

jQuery 的版本并不重要,您需要本地副本还是热链接取决于您Google 版本bookmark.js 与OP的代码几乎完全相同:

$ cat /scripts/bookmark.js 
/* simple cross-browser script for adding a bookmark 
    source: http://stackoverflow.com/questions/992844/add-to-browser-favourites-bookmarks-from-javascript-but-for-all-browsers-mine-do 
*/ 
function addToFavorites(url, name) { 
    if (window.sidebar) { // Mozilla Firefox 
        window.sidebar.addPanel(name, url, ""); 
    } else if (window.external) { // IE 
        window.external.AddFavorite(url, name); 
    } else if (window.opera && window.print) { 
        window.external.AddFavorite(url, name); 
    } else { 
        alert("Sorry! Your browser doesn't appear to support this function."); 
    } 
} 

希望有用。

After discovering - like Edison! - a bunch of ways this doesn't work, I eventually came across this page that says adding bookmarks via JS is explicitly disabled in Chrome. Unfortunately it does not explain why.

Update: I was asked to expand this answer by another SO user...

My links and buttons for this function all have a class="addbookmark" associated with them. When the user agent is Chrome, I use some jQuery to disable the links and explain why:

<script type="text/javascript" src="/scripts/jquery-1.4.2.min.js"></script> 
<script type="text/javascript" src="/scripts/bookmark.js"></script> 
<script> 
    title='A Label for this Bookmark, ie title of this page'; // for example, not really generated this way... 

    $jQuery(document).ready(function(){ 
        // chrome does not permit addToFavorites() function by design 
        if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) { 
            $('.addbookmark').attr({ 
                title: 'This function is not available in Google Chrome. Click the star symbol at the end of the address-bar or hit Ctrl-D to create a bookmark.', 
                href: 'javascript:return false' 
            }) 
            .css({opacity: .25});       // dim the button/link 
        } 
    }); 
</script> 

And then elsewhere on the page:

 <td rowspan="2" class="noprint" style="width:24px;"> 
     <a class="addbookmark" title="Save a Bookmark for this page" 
        href="javascript:addToFavorites(location.href,title)"> 
        <img style="width:24px; height:24px; padding-top:2px;" src="/images/bookmark.gif"></a> 
 </td> 

... which is by no means perfect, but it seems one's options are fairly limited.

The version of jQuery isn't important, and it's up to you whether you want a local copy or hot-link to the google version. bookmark.js is pretty much exactly as per the OP's code:

$ cat /scripts/bookmark.js 
/* simple cross-browser script for adding a bookmark 
    source: http://stackoverflow.com/questions/992844/add-to-browser-favourites-bookmarks-from-javascript-but-for-all-browsers-mine-do 
*/ 
function addToFavorites(url, name) { 
    if (window.sidebar) { // Mozilla Firefox 
        window.sidebar.addPanel(name, url, ""); 
    } else if (window.external) { // IE 
        window.external.AddFavorite(url, name); 
    } else if (window.opera && window.print) { 
        window.external.AddFavorite(url, name); 
    } else { 
        alert("Sorry! Your browser doesn't appear to support this function."); 
    } 
} 

Hope that's useful.

意中人 2024-07-31 05:41:28

我刚刚在以下版本中测试了此脚本:

Win

  • IE 6.0、IE 7.0、IE 8.0
  • Firefox 2.0、Firefox 3.6.3
  • Safari 3.1.2、Safari 3.2.3
  • Opera 9.00
  • Google Chrome 8.0

Mac

  • Firefox 3.6.13
  • Safari 5.0.1
  • Opera 11.0
  • 谷歌浏览器8.0

    <前><代码>/*
    * GlamThumbs 团队版权所有 2010。
    *
    * 如何使用脚本:
    * 将此代码添加到您的页面内部 head 标签之间
    * <脚本类型=“text/javascript”src=“ATBookmarkApp.js”>
    * 添加带有 void href 的锚点,如下所示:
    * 为我们添加书签
    *
    */

    ATBookmarkApp = 函数 () {
    var isIEmac = false; /*@cc_on @if(@_jscript&&!(@_win32||@_win16)&&
    (@_jscript_version<5.5)) isIEmac=true; @结尾 @*/
    var isMSIE = (-[1,]) ? 假:真;
    var cjTitle = 文档.标题;
    var cjHref = 位置.href;

    函数热键(){
    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'; // 征服者
    } else if (window.home || isWebkit || isIEmac || isMac) {
    str = (isMac ? '命令/Cmd' : 'CTRL') + ' + D'; // Netscape、Safari、iCab、IE5/Mac
    }
    return ((str) ? '按 ' + str + ' 将此页加入书签。' : str);
    }

    函数 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);
    }
    }
    如果 (rv > - 1) {
    如果(rv >= 8.0){
    返回真;
    }
    }
    返回假;
    }

    函数 addBookmark(a) {
    尝试 {
    if (typeof a == "object" && a.tagName.toLowerCase() == "a") {
    a.style.cursor = '指针';
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) {
    window.sidebar.addPanel(cjTitle, cjHref, ""); // 壁虎
    返回假;
    } else if (isMSIE && typeof window.external == "object") {
    如果 (isIE8()) {
    window.external.AddToFavoritesBar(cjHref, cjTitle); // IE 8
    } 别的 {
    window.external.AddFavorite(cjHref, cjTitle); // IE <=7
    }
    返回假;
    } else if (window.opera) {
    a.href = cjHref;
    a.标题 = cjTitle;
    a.rel = '侧边栏'; // 歌剧 7+
    返回真;
    } 别的 {
    警报(热键());
    }
    } 别的 {
    throw "发生错误。\r\n注意,只允许使用标记名!";
    }
    } 捕获(错误){
    警报(错误);
    }

    }

    返回 {
    添加书签 : 添加书签
    }
    }();

I just tested this script in:

Win

  • IE 6.0, IE 7.0, IE 8.0
  • Firefox 2.0, Firefox 3.6.3
  • Safari 3.1.2, Safari 3.2.3
  • Opera 9.00
  • Google Chrome 8.0

Mac

  • Firefox 3.6.13
  • Safari 5.0.1
  • Opera 11.0
  • Google Chrome 8.0

    /*
    * Copyright 2010 by GlamThumbs Team.
    *
    * How To Use The Script:
    * add to your page this code between inside head tags
    * <script type="text/javascript" src="ATBookmarkApp.js"></script> 
    * add anchor with void href like this: 
    * <a href="javascript:void(0)" onClick="return BookmarkApp.addBookmark(this)">bookmark us</a> 
    * 
    */
    
    ATBookmarkApp = function () {
        var isIEmac = false; /*@cc_on @if(@_jscript&&!(@_win32||@_win16)&& 
    (@_jscript_version<5.5)) isIEmac=true; @end @*/
        var isMSIE = (-[1,]) ? false : true;
        var cjTitle = document.title;
        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.\r\nNote, only A tagname is allowed!";
                }
            } catch (err) {
                alert(err);
            }
    
        }
    
        return {
            addBookmark : addBookmark
        }
    }();
    
人间☆小暴躁 2024-07-31 05:41:28

您可以随时提醒客户按 ctr+D。 这在所有浏览器中都是通用的。 它很俗气,但对客户同样有用。

CTRL + D——适用于 Windows
CMD + D——对于 Mac

You can always alert the client to press ctr+D. This is universal across all browsers. It's tacky, but just as useful to the client.

CTRL + D -- for Windows
CMD + D -- for Mac

失眠症患者 2024-07-31 05:41:28

我无法让上面的例子工作。 无论如何,最初问题的答案“它在 Chrome 中不起作用,我也没有收到错误消息说“不支持”。”是因为

else if (window.external) { // IE 

chrome 行实际上通过了此测试,然后显然无法添加书签。 我将此行更改为

else if(window.external && !window.chrome)  // IE

,现在您收到“不支持”消息。 我实际上删除了这条消息并调用函数 hotKeys() 来获取更有意义的警报。 我必须做一些改变才能让它发挥作用

function showHotKeys() 
{ 
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 || isMac) { 
    str = (isMac ? 'Command/Cmd' : 'CTRL') + ' + D'; // Netscape, Safari, iCab
} 
return ((str) ? 'Press ' + str + ' to bookmark this page.' : str); 
} 

I couldnt get the above example to work. Anyway the answer to the original question 'its not working in CHROME and i don't get my error msg saying "not supported" either..' is due to the line

else if (window.external) { // IE 

chrome actually passes this test and then obiously fails to add a bookmark. I changed this line to

else if(window.external && !window.chrome)  // IE

and now you get the 'not supported' message. I actually removed this message and called the function hotKeys() to get a more meaningful alert. I had to make a few changes to get that to work

function showHotKeys() 
{ 
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 || isMac) { 
    str = (isMac ? 'Command/Cmd' : 'CTRL') + ' + D'; // Netscape, Safari, iCab
} 
return ((str) ? 'Press ' + str + ' to bookmark this page.' : str); 
} 
余生再见 2024-07-31 05:41:28

我在 jQuery 帮助下的方法。
在 IE 6-8、Fx 1-25、Opera 7-14 中测试。 在 Chrome、Saf 中优雅地降级。

CSS:

.no-js .link-bookmark {
   display: none;
}

JS:

/* ... Bookmark current page ... */
var $favLink = $('.link-bookmark');

if ( window.sidebar || 'AddFavorite' in window.external || window.opera ) {
    $favLink.show();
}

// add a 'rel' attrib if Op 7+ && Fx >= 23
if ( window.opera || window.sidebar ) {
    var $favLinkAttrRel = $favLink.attr('rel');
    if ( typeof $favLinkAttrRel !== "undefined" && $favLinkAttrRel !== false ) { // don't overwrite the rel attr if already set
        $favLink.attr('rel', 'sidebar');
    }
}

$favLink.click(function( event ) {
//event.preventDefault(); // prevent the anchor tag from sending the user off to the link
var url = this.href;
var $title = $('title').text();

// IE Favorite
if ( 'AddFavorite' in window.external ) {
    event.preventDefault();
    window.external.AddFavorite(url, $title);
}
// Fx <23 Bookmark, 'addPanel' not available from v23 on any more.
else if ( 'addPanel' in window.sidebar ) {
    event.preventDefault();
    window.sidebar.addPanel($title, url, '');
}
// Op 7+ && Fx >= 23
else if ( window.opera || window.sidebar ) {
    $favLink.attr('title', $title);
    return true; // do nothing - the rel="sidebar" should do the trick
}
// for Saf, Konq etc - browsers who do not support bookmarking scripts
else {
    event.preventDefault();
    alert('Your browser doesn\'t support the bookmark functionality,'
    + 'please add this page to your bookmarks manually.');
} 
});

My approach with help of jQuery.
Tested in IE 6-8, Fx 1-25, Opera 7-14. Degrades gracefully in Chrome, Saf.

CSS:

.no-js .link-bookmark {
   display: none;
}

JS:

/* ... Bookmark current page ... */
var $favLink = $('.link-bookmark');

if ( window.sidebar || 'AddFavorite' in window.external || window.opera ) {
    $favLink.show();
}

// add a 'rel' attrib if Op 7+ && Fx >= 23
if ( window.opera || window.sidebar ) {
    var $favLinkAttrRel = $favLink.attr('rel');
    if ( typeof $favLinkAttrRel !== "undefined" && $favLinkAttrRel !== false ) { // don't overwrite the rel attr if already set
        $favLink.attr('rel', 'sidebar');
    }
}

$favLink.click(function( event ) {
//event.preventDefault(); // prevent the anchor tag from sending the user off to the link
var url = this.href;
var $title = $('title').text();

// IE Favorite
if ( 'AddFavorite' in window.external ) {
    event.preventDefault();
    window.external.AddFavorite(url, $title);
}
// Fx <23 Bookmark, 'addPanel' not available from v23 on any more.
else if ( 'addPanel' in window.sidebar ) {
    event.preventDefault();
    window.sidebar.addPanel($title, url, '');
}
// Op 7+ && Fx >= 23
else if ( window.opera || window.sidebar ) {
    $favLink.attr('title', $title);
    return true; // do nothing - the rel="sidebar" should do the trick
}
// for Saf, Konq etc - browsers who do not support bookmarking scripts
else {
    event.preventDefault();
    alert('Your browser doesn\'t support the bookmark functionality,'
    + 'please add this page to your bookmarks manually.');
} 
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文