発見した後 - エジソンのように!-これが機能しない方法がたくさんありますが、最終的に、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.");
}
}
それが役に立つことを願っています。