Silverlight Applications - Embedding in Web pages
Date: 2011-03-22
Silverlight Embedding on a Page
Gennerally there are several ways to embedd Silverlight Applications on a html page:
Reference:
- http://msdn.microsoft.com/en-us/library/cc838145(v=vs.95).aspx
- http://developer.yahoo.com/dotnet/silverlight/embeddingobject.html
Embedding with HTML object tag (Using pure object notation)
Preffered way in ASP.net 3.5 according to......
Overview
Microsoft recommends using the <object> tag method of embedding a Silverlight application on a web page. This method works in all browsers supported by Silverlight and does not require JavaScript to be enabled. It also provides an easy way to provide fallback content if Silverlight isn't installed.
You can also use the JavaScript method and helper files if you need greater control over the embedding or install/upgrade process.
Using the <object> Tag
The following example shows the minimum code required to embed the Silverlight plug-in on a web page using the HTML <object> tag.
<object type="application/x-silverlight-2" data="data:application/x-silverlight," width="300" height="300"> <param name="source" value="/ClientBin/HolisticWare.WWWLogo.EXE_SL3.xap"/> <object>
In most cases, you will want to add additional parameters and HTML elements to provide a complete user experience with increased cross browser support. A more complete sample can be seen at the end of this page.
Parameters
Below is a list of available parameters that can be passed to the plug-in using the <param> tag.
| Parameter | Description | Type |
|---|---|---|
| allowHtmlPopupWindow | Specifies whether the HtmlPage.PopupWindow method is allowed. Defaults to true for applications in the same domain, otherwise false. |
Boolean |
| autoUpgrade | Specifies whether the plug-in should attempt to upgrade if minRuntimeVersion is newer than the current Silverlight version. |
Boolean |
| background | Plug-in background color. Default is null (white). |
Color with or without alpha (RGB, ScRGB) |
| enablehtmlaccess | Specifies whether the plug-in has full access to the browser DOM. Defaults to true for applications in the same domain, otherwise false. |
Boolean |
| initparams | User-defined string of parameters. | String or comma separated string (SL 1.0), comma separated key=value pairs (SL 2) |
| maxframerate | Specifies the maximum number of frames per second that the plug-in can render. The default is 60. | Integer |
| minRuntimeVersion | Specifies the earliest version of the Silverlight plug-in required. | Version number |
| onerror | Error handler for parse and native code run-time errors. | JavaScript function name |
| onfullscreenchanged | Function to call when the FullScreen property changes. |
JavaScript function name |
| onload | Function to call when the plug-in has finished loading in the DOM. | JavaScript function name |
| onresize | Function to call when the plug-in size changes. | JavaScript function name |
| onsourcedownloadcomplete | Function to call when the source download has completed. | JavaScript function name |
| onsourcedownloadprogresschanged | Function to call when the source download progress changes. | JavaScript function name |
| source | Specifies the address or relative path of either an initial XAML file or XAP. | URI |
| splashscreensource | Specifies a XAML page to use as the splash screen. | URI |
| windowless | Specifies the rendering mode for the plug-in for Windows versions of Silverlight. The default is false. |
Boolean |
Example
The following example shows a full web page that embeds the Silverlight plug-in and runs a very simple application. It highlights providing basic alternate content when Silverlight isn't installed and also a workaround to prevent Safari from caching the page.
<html>
<head>
<title>Sample: Embedding the Silverlight plug-in</title>
<style type="text/css">
html, body { height: 100%; overflow: auto; }
body { padding: 0; margin: 0; }
#silverlightControlHost { height: 100%; }
</style>
</head>
<body>
<div id="silverlightControlHost">
<object data="data:application/x-silverlight,"
type="application/x-silverlight-2"
width="100%" height="100%">
<param name="source" value="/ClientBin/HolisticWare.WWWLogo.EXE_SL3.xap"/>
<param name="background" value="black" />
<!-- Set the required version and auto-update option -->
<param name="minRuntimeVersion" value="2.0.31005.0" />
<param name="autoUpgrade" value="true" />
<!-- Provide alternate content when Silverlight isn't installed
-->
<a href="http://go.microsoft.com/fwlink/?LinkID=124807"
style="text-decoration: none;">
<img src="http://go.microsoft.com/fwlink/?LinkId=108181"
alt="Get Microsoft Silverlight" style="border-style:
none"/>
</a>
</object>
<!-- Prevent Safari from caching the page -->
<iframe
style="visibility:hidden;height:0;width:0;border:0px"></iframe>
</div>
</body>
</html>
Preffered way in ASP.net 3.5
<div id="silverlightControlHost"> <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%"> <param name="source" value="ClientBin/HolisticWare.WWWLogo.EXE_SL3.xap"/> <param name="onError" value="onSilverlightError" /> <param name="background" value="white" /> <param name="minRuntimeVersion" value="4.0.50826.0" /> <param name="autoUpgrade" value="true" /> <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none"> <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/> </a> </object> <iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe> </div> </asp:Silverlight>
Embedding with JavaScript
This method might have problems if javascript is disabled in browser (on client side).
Overview
Microsoft provides JavaScript helper files that make embedding Silverlight applications on a web page easy. These helper files provide a consistent method for passing in parameters and take care of cross-browser differences in addition to providing users a seamless install experience if they don't have Silverlight installed. These files require JavaScript to be enabled. For a non-JavaScript method, see Embedding using the <object> tag.
It is important to provide users who don't have Silverlight installed the best possible user experience. This includes providing the user with a preview of the content they will get in return for taking the time to install, keeping them within your page and automatically showing the Silverlight enabled content once the installation has completed. Unfortunately, currently all other browsers except Internet Explorer on Windows will require the user to restart their browser after installation. More details can be found in the Silverlight Installation Experience Guide provided by Microsoft.
An easy way to test the experience users without Silverlight will get is to use Internet Explorer 7's add-on manager to temporarily disable the Silverlight "Microsoft Silverlight" or "AgControl Class" add-on.
Using the Helper Files
Silverlight.js & CreateSilverlight.js
The two helper files Microsoft provides are Silverlight.js and CreateSilverlight.js. The former is the main file you will need, while the latter is an optional encapsulation of the settings that will be passed when the plug-in and application are created. These files, including their localized versions, can be found in the Silverlight SDK Tools folder.
Silverlight.js is minified (8kB) and contains the code required to embed the Silverlight plug-in. CreateSilverlight.js on the other hand only contains a call-thru to Silverlight.js with a set of parameters.
To embed a Silverlight application on a web page, you will need the following on your page:
- A
<script>tag that references theSilverlight.jsfile. - An HTML block element, usually a
<div>tag, that will contain the Silverlight plug-in and thus the application. - A
<script>tag that contains code (usuallycreateObjectEx();) to render the plug-in. - (Optional) A
<script>tag that references theCreateSilverlight.jsfile.
Since the CreateSilverlight.js file essentially only contains one function, you may want to avoid using this file to minimize unnecessary network calls. Instead, consider including the code directly within your page or, even better, within another external JavaScript file, such as the file where you have your application code. See Rule 8 - Make JavaScript and CSS External and the YDN Performance blog for additional tips.
The Silverlight Class
The Silverlight.js file creates a class named Silverlight that provides methods and properties to create the application on the page and also to help get information about the environment, such as whether Silverlight is installed and which browser is running.
The following table lists public properties and methods of the Silverlight class.
| Name | Description |
|---|---|
available |
A property that returns a Boolean value indicating whether any version Silverlight has been installed. |
createObject(...) |
Creates a Silverlight application with the given list of parameters. |
createObjectEx(parametersObject) |
Creates a Silverlight application with parameters given in a JSON dictionary. |
isInstalled(versionString) |
A method that returns a Boolean value indicating whether the specified version of Silverlight has been installed. |
supportedUserAgent() |
A method that returns a Boolean value indicating whether the current operating system and browser combination is supported. |
ua.Browser |
A property that gets a string representing the running browser. Values returned include Firefox, MSIE, and Safari. |
ua.OS |
A property that gets a string representing the running operating system. Values returned include Unsupported, MacIntel, MacPPC, and Windows. |
The createObject() & createObjectEx() Methods
The createObject and createObjectEx are the methods used to create the Silverlight application on a page. The difference between the two methods is that createObject takes parameters as method arguments in a predefined order and createObjectEx takes a single JSON object with named key-value pairs. Thus createObjectEx is less prone to typing errors and also provides a cleaner way to use built-in default values.
The following table lists the required parameters.
| Name | Description |
|---|---|
source |
The source XAML file or ID of an inline XAML script block prefixed with #. |
parentElement |
The HTML block element that will contain the application. |
id |
The HTML element ID for the newly created application. |
properties |
A JSON object containing initialization properties, such as width, height, and version. |
events |
A JSON object containing global level event handlers onError and onLoad. |
The detailed method signatures and full list of available parameters that can be set can be found in the Silverlight SDK documentation .
Detecting If Silverlight Is Installed
You can use the Silverlight.isInstalled(version) method to check if the required version of Silverlight is installed on the client. This will allow your site to provide additional information and sample content to users who haven't installed Silverlight yet or don't have the correct version.
Example
The following example loads a Silverlight application from the myApplication.xaml file in the MyApplication folder. If Silverlight isn't installed, it will display a preview image and reattempt to display the application every three seconds until the installation has completed.
<html>
<head>
<title>Simple Silverlight Embedding Sample</title>
<!-- Include the install/embed helper file -->
<script type="text/javascript" src="/js/Silverlight.js"></script>
<style type="text/css">
.noSL { padding-top: 30px;
background: url(MyApplication1/preview.png) no-repeat top left; }
</style>
</head>
<body>
<div id="myApplicationHolder" style="width:800px; height:600px" />
<script type="text/javascript">
function createMyApplication1() {
var holder = document.getElementById("myApplicationHolder");
// Check if Silverlight is installed
if(Silverlight.isInstalled("1.00") != true) {
// Set a preview image for our application
holder.className = "noSL";
// Attempt to refresh the Silverlight control after install
setTimeout(createMyApplication1, 3000);
} else {
// Clear the preview image
holder.className = "";
}
// Create a Silverlight application using as many defaults as possible
Silverlight.createObjectEx({source: "MyApplication1/MyApplication1.xaml",
parentElement: holder,
id: "myApplication",
properties: {
width: "800",
height: "600",
inplaceInstallPrompt: true,
version: "1.0"},
events: {}
});
}
// Attempt to create the Silverlight application for the first time
createMyApplication1();
</script>
</body>
</html>
ASP.net server side controls (asp:silverlight control)
This method was used in of Silverlight SDK version 2 and removed in version 3. Method was based on the usage of asp:ScriptManager and asp:Silverlight controls. It can still be used in version 3, but use object notation is preferred,
<%@ Page Language="VB" AutoEventWireup="true" %>
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html style="height:100%;">
<head runat="server">
<title>Test Page For myExample</title>
</head>
<body style="height:100%;margin:0;">
<form id="form1" runat="server" style="height:100%;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div style="height:100%;">
<asp:Silverlight ID="Xaml1" runat="server" Source="/ClientBin/HolisticWare.WWWLogo.EXE_SL3.xap"
MinimumVersion="2.0" Width="100%" Height="100%" />
</div>
</form>
</body>
</html>
<object type="application/x-silverlight-2"
data="data:application/x-silverlight,"
width="300" height="300">
<param name="source" value="SilverlightApplication1.xap"/>
<object>
<html>
<head>
<title>Simple Silverlight Embedding Sample</title>
<!-- Include the install/embed helper file -->
<script type="text/javascript" src="../../../js/Silverlight.js"></script>
<style type="text/css">
.noSL { padding-top: 30px;
background: url(MyApplication1/preview.png) no-repeat top left; }
</style>
</head>
<body>
<div id="myApplicationHolder" style="width:800px; height:600px" />
<script type="text/javascript">
function createMyApplication1() {
var holder = document.getElementById("myApplicationHolder");
// Check if Silverlight is installed
if(Silverlight.isInstalled("1.00") != true) {
// Set a preview image for our application
holder.className = "noSL";
// Attempt to refresh the Silverlight control after install
setTimeout(createMyApplication1, 3000);
} else {
// Clear the preview image
holder.className = "";
}
// Create a Silverlight application using as many defaults as possible
Silverlight.createObjectEx({source: "MyApplication1/MyApplication1.xaml",
parentElement: holder,
id: "myApplication",
properties: {
width: "800",
height: "600",
inplaceInstallPrompt: true,
version: "1.0"},
events: {}
});
}
// Attempt to create the Silverlight application for the first time
createMyApplication1();
</script>
References
- http://msdn.microsoft.com/en-us/library/cc189004%28VS.95%29.aspx#Y911
- Silverlight and DOM
- HTML bridge