First we need a decent javascript function that will handle this for most browsers. Here is one:
function bookmarksite(title, url)
{
if(document.all)
window.external.AddFavorite(url,title);
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()
{
InitializeComponent();
// 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];
head.AppendChild(script);
// 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!");
a.SetStyleAttribute("font-size","20pt");
doc.GetElementsByTagName("form")[0].AppendChild(a);
}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.