Silverlight: Dynamically add "favorites" bookmark link to Page

Somebody posted this question at the Silverlight Forums and I figured I'd give it a shot. What we want is a generic "cross-browser" Add-to-Favorites script, and we want to be able to add this and a link that calls it to the underlying Page from within our Silverlight App running on the page.


First we need a decent javascript function that will handle this for most browsers. Here is one:

function bookmarksite(title, url)
   else if(window.sidebar)
       window.sidebar.addPanel(title, url, '')

Our "link" would then need to look like this:

<A href="javascript:bookmarksite(document.title, location.href);">Bookmark This Page</A>

Here is all the code we would need to do this in the Silverlight Page constructor, in Page.xaml.cs:

private HtmlDocument doc;
        public Page()
            // our new code:
            doc = HtmlPage.Document;
            // let's give the page a custom title...
            doc.GetElementsByTagName("title")[0].SetProperty("text", "ABRACADABRA!");
            // create our script function as a string
            string scr ="function bookmarksite(title, url){if(document.all)window.external.AddFavorite(url,title);else if(window.sidebar)window.sidebar.addPanel(title, url, '')}";
            // create a new script element to add to the page
            HtmlElement script = HtmlPage.Document.CreateElement("script");
            // set the type attribute
            script.SetAttribute("type", "text/javascript");
            // assign the script text
            script.SetProperty("text", scr);
            // append the script element to the document
            HtmlElement head = doc.GetElementsByTagName("head")[0];
            // create a new "a" tag
            var a = doc.CreateElement("a");
            // set the href to fire off our javascript function
            a.SetAttribute("href", "javascript:bookmarksite(document.title, location.href);");
            a.Id = "link1";
            a.SetAttribute("innerText", "Bookmark This Page!");
The above will inject the script tag with its function into the HEAD element of the document, and add the A link into the FORM element.  You can download the complete Visual Studio 2008 Silverlight solution here.
By Peter Bromberg   Popularity  (3284 Views)