Arjun Vasudevan
Arjun Vasudevan

Reputation: 872

Running a JavaScript code when a browser bookmark is clicked

I've written a code that has successfully created a bookmark for any of the following browsers - IE, Firefox and Opera.

<script language="JavaScript" type="text/javascript">
    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();
        }
    }
</script>

Now I want my bookmark to run a piece of JavaScript code instead of surfing to Google, when the user clicks on it.

Upvotes: 1

Views: 12123

Answers (2)

adifire
adifire

Reputation: 610

You can try putting the js code in an html and then bookmark that html.

Upvotes: 3

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

This is called a bookmarklet. You could try replacing 'http://google.com' with "javascript:alert('Annoying message');". However, Firefox at least doesn't allow adding bookmarklets using this API. I suspect IE and Opera may be the same.

Upvotes: 7

Related Questions