Search code examples
javascriptbookmarks

Adding Browser Bookmarks using JavaScript


I have an ASP.NET web page having a button in it. Clicking the button, a bookmark should be saved in the browser and when the user clicks the bookmark, it should surf to http://google.com.

How do I make sure that it works with almost all the standard browsers or at least with IE, Mozilla Firefox, Opera and Google Chrome.

Another case, I create a 2nd bookmark also in the same way. But when the user clicks upon the 2nd bookmark, it should run a piece of JavaScript code.


Solution

  • I wrote this piece of code which works for IE, Firefox and Opera (unfortunately it doesn't work for Google Chrome).

    function bookmark()
    {
        var title = 'Google';
        var url = 'http://google.com';
    
        if (document.all) // Check if the browser is Internet Explorer
            window.external.AddFavorite(url, title);
    
        else if (window.sidebar) //If the given browser is Mozilla Firefox
            window.sidebar.addPanel(title, url, "");
    
        else if (window.opera && window.print) //If the given browser is Opera
        {
            var bookmark_element = document.createElement('a');
            bookmark_element.setAttribute('href', url);
            bookmark_element.setAttribute('title', title);
            bookmark_element.setAttribute('rel', 'sidebar');
            bookmark_element.click();
        }
    }