0

I've seen a couple of js snippets to bookmark a page, like this one: http://www.thewebflash.com/2014/12/how-to-add-cross-browser-add-to.html

Basically they call different js method depending on the browser, dynamically create an href with rel=sidebar in ff, or prompt the user to manually add it if it's not supported on that browser.

I was wondering what would be the cleanest way to achieve this in an angular app? I searched for a directive that could accomplish it but couldn't find any.

opensas
  • 60,462
  • 79
  • 252
  • 386

1 Answers1

2

Here is a simple directive implementing that feature:

angular.module("myApp", [])
    .directive("bookmarkPage", function ($window, $location) {
    return {
        restrict: "AEC",
        link: function (scope, element, attrs) {
            $(element).click(function (e) {
                var bookmarkURL = window.location.href;
                var bookmarkTitle = document.title;
                var triggerDefault = false;

                if (window.sidebar && window.sidebar.addPanel) {
                    // Firefox version < 23
                    window.sidebar.addPanel(bookmarkTitle, bookmarkURL, '');
                } else if ((window.sidebar && (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)) || (window.opera && window.print)) {
                    // Firefox version >= 23 and Opera Hotlist
                    var $this = $(this);
                    $this.attr('href', bookmarkURL);
                    $this.attr('title', bookmarkTitle);
                    $this.attr('rel', 'sidebar');
                    $this.off(e);
                    triggerDefault = true;
                } else if (window.external && ('AddFavorite' in window.external)) {
                    // IE Favorite
                    window.external.AddFavorite(bookmarkURL, bookmarkTitle);
                } else {
                    // WebKit - Safari/Chrome
                    alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Cmd' : 'Ctrl') + '+D to bookmark this page.');
                }

                return triggerDefault;
            });
        }

    }
});

Still you can replace those window and window.loaction with $window and $location to make it easily testable.

In your HTML:

  <a id="bookmark-this" href="#" title="Bookmark This Page" bookmark-page>Bookmark This Page</a>
mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • thanks a lot, it works ok for chrome (that is, it display an alert telling me to press ctrl-d), but with firefox it gives me the following angular error: "TypeError: a.split is not a function" (I also had to add a "var $ = angular.element;") – opensas Apr 12 '15 at 06:04
  • No. Both $ and angular.element are not same. – mohamedrias Apr 12 '15 at 06:21