Click to Rate and Give Feedback
MSDN
MSDN Library
Web Development
Silverlight
 Using Silverlight.js
Silverlight 2
Using Silverlight.js
[This topic is pre-release documentation and is subject to change in future releases. Blank topics are included as placeholders.]

Silverlight.js is a JavaScript helper file that is provided in the Silverlight SDK. You can call functions defined in this file in order to initialize Silverlight plug-in instances on a Web page. Silverlight.js also contains utility functions for determining the client's installed version of the plug-in.

This topic contains the following sections.

Note:

You can also use the <OBJECT> tag to configure and instantiate the Silverlight plug-in control. For more information, see Instantiating a Silverlight Plug-In (Silverlight 2).

To use a Silverlight plug-in on a Web page, using Silverlight.js functions for initialization, you define an HTML page that includes the following:

  1. A <SCRIPT> tag that references a location for Silverlight.js.

  2. An HTML block element such as a <DIV> tag that encloses the Silverlight plug-in. When the CreateObject and CreateObjectEx methods execute, this block element becomes the location in which the methods will write their HTML output. This block element must have a unique ID attribute value in the HTML DOM.

  3. A <SCRIPT> call embedded within that block element that calls CreateObject or CreateObjectEx, or an equivalent scripting technique that targets the block element as the scope when CreateObject or CreateObjectEx methods execute, and also provides an HTML DOM reference to the hosting block.

The following HTML example shows these three aspects in an HTML page that hosts the Silverlight plug-in.

<head>
  <title>My Silverlight Application</title>

  <!-- Helper files for initializing and creating the Silverlight plug-in -->
  <script type="text/javascript" src="js/Silverlight.js"></script>
</head>
<body>
  <div id="slPluginHost" >
    <script type="text/javascript">
      // Create a variable that references the HTML element that hosts the plug-in.
      var parentElement = document.getElementById("slPluginHost");
      // Initialize and create the plug-in.
      Silverlight.createObject(
        "package.xap",                      // Source property value.
        parentElement,                      // DOM reference to hosting HTML block tag.
        "myPlugin",                         // Unique plug-in ID value.
        {                                   // Plug-in properties.
            width:'1024',                   // Width of rectangular region of plug-in in pixels.
            height:'530',                   // Height of rectangular region of plug-in in pixels.
            background:'blue',             // Background color of plug-in.
        },
        { //Plug-in event object
            onError:null,                   // OnError property value -- event-handler function name.
            onLoad:null                     // OnLoad property value -- event-handler function name.
        },
        null,                               // initParams -- user-settable string for information passing.
        null);                              // Context value -- passed to Silverlight.js onLoad event handlers.
}
    </script>
  </div>
</body>
...

Previous documentation on Silverlight instantiation mentions a CreateSilverlight method and/or a file named CreateSilverlight.js (now deprecated). The file and method were just a recommendation for how to encapsulate calls to CreateObject / CreateObjectEx, rather than including the call and its parameters as inline code in the hosting HTML block. For instance, you might instead have this HTML:

<!--head and html tags omitted-->
<body>
  <div id="slPluginHost" >
    <script type="text/javascript">
      // Create a variable that references the HTML element that hosts the plug-in.
      var parentElement = document.getElementById("slPluginHost");
      
      // Initialize and create the plug-in.
      createSilverlight();
    </script>
  </div>
</body>

CreateObject is a parameterized function, whereas CreateObjectEx is a tokenized function for JSON (JavaScript object notation). CreateObjectEx is really just a wrapper around a CreateObject call. It is a purely matter of personal preference and programming style whether to use CreateObject versus CreateObjectEx.

The following JavaScript example shows a call to Silverlight.CreateObjectEx, with parameter values corresponding to the previous example.

JScript
function createSilverlightEx()
{  
    Silverlight.createObjectEx({
        source: 'plugin.xaml',          // Source property value.
        parentElement:parentElement,    // DOM reference to hosting DIV tag.
        id:'myPlugin',                  // Unique plug-in ID value.
        properties:{                    // Plug-in properties.
            width:'1024',               // Width of rectangular region of plug-in, in pixels.
            height:'530',               // Height of rectangular region of plug-in, in pixels.
            background:'white',         // Background color of plug-in.
            framerate:'24',             // MaxFrameRate property value.
        events:{
            onError:null,               // OnError property value -- event-handler function name.
            onLoad:null},               // OnLoad property value -- event-handler function name.
        initParams:null,                // initParams property value -- user-settable string for information passing.
        context:null});                 // Context value -- passed to Silverlight.js onLoad event handlers.
}

The following parameters are passed to the Silverlight.CreateObject and Silverlight.CreateObjectEx methods. Some of these parameters correspond to the resulting output in the form of <OBJECT> or <EMBED> tags.

Also, some parameters correspond to a property in the Silverlight plug-in's object model, so you can retrieve the values of the initialization parameters in run-time code. In the Silverlight managed programming model, the object model values are most often found on the SilverlightHost class, which in turn is accessible from Application.

  • source -- Refers to the XAML content file. Accessible as the Source property of the Silverlight plug-in in the unmanaged JavaScript programming model, or Source in the managed programming model.

  • parentElement -- Refers to the block element in the HTML file that becomes the host (parent in the HTML DOM) element for the Silverlight plug-in after it is instantiated.

  • id -- Refers to the unique identifier of the instantiated Silverlight plug-in within the HTML DOM.

  • properties -- Refers to the set of Silverlight plug-in initialization properties. (See tables below.)

  • events -- Refers to the set of Silverlight plug-in events that can be set at initialization. (See tables below.)

  • initParams -- Refers to the set of user-defined initialization parameters. For more information, see InitParams.

  • context -- Refers to the unique identifier that can be passed as a parameter to an OnLoad event handler function that can be shared by multiple Silverlight plug-ins on the same Web page. This value uniquely identifies which plug-in was loaded without having to check the HTML DOM. For more information, see "Using the Silverlight.js OnLoad Event" section of this topic, or Writing Event Handlers for the OnLoad Event.

The following table lists the parameters that can be defined as Silverlight plug-in initialization properties (within the properties parameter).

Parameter

Description

width

Defines the width of the rectangular region that displays the Silverlight content. Sets the plug-in's width property. This property is exposed through the HTML DOM. The default unit of measurement is pixels. You can also specify the width as a percentage of the displayable area of the tag that contains the plug-in (for example, "40%"). The default value is 0. This value can be checked at run time through ActualWidth, which gives the actual pixel width for cases where the original width was specified as a percentage. Caution: validity not guaranteed prior to OnResize.

height

Defines the height of the rectangular region that displays the Silverlight content. Sets the plug-in's height property. This property is exposed through the DOM. The default unit of measurement is pixels. You can also specify the height as a percentage of the displayable area of the tag that contains the plug-in (for example, "50%"). The default value is 0. This value can be checked at run time through ActualHeight, which gives the actual pixel height for cases where the original height was specified as a percentage. Caution: validity not guaranteed prior to OnResize.

background

Specifies the background color of the rectangular content region that displays XAML content. Generally this is behind the content defined in the XAML, and depending on your design might often be completely obscured by your Silverlight content. This value can be retrieved at run time through the Background property. See Background (Silverlight Plug-in) for valid parameter settings for the background parameter. Or see Color; the syntaxes listed in either topic each describe the same string conversion conventions. The default value is null, which is equivalent to the named color White for rendering purposes.

isWindowless

Determines whether the plug-in displays as a windowless plug-in. This value can be retrieved at run time through the Windowless property. If the value is set to true and the Background property value specifies an alpha value, the color value is blended with the HTML page. The default value is false. On Macintosh, the plug-in always acts as a windowless plug-in, and the value of this parameter is ignored in run-time behavior.

frameRate

Specifies the maximum number of frames to render per second. This value can be retrieved or set at run time through the MaxFrameRate property. The actual frame rate that Silverlight content renders depends on system load performance.

inplaceInstallPrompt

Deprecated; do not use.

version

Specifies the specific Silverlight version required to run the application. The version initialization parameter is compared with the version of the currently installed Silverlight runtime. If the installed version is less than the requested version, an installation prompt is presented instead of the control.

There is no corresponding run-time property.

ignoreBrowserVer

Deprecated; do not use.

enableHtmlAccess

Specifies whether the Silverlight plug-in allows hosted content or its runtime to access the HTML DOM.

true allows hosted content access to the browser DOM. false disables the HTML DOM bridge APIs. The default value is false.

For more information about the bridge APIs, see HTML Bridge: Interaction Between HTML and Managed Code.

You cannot change this value after plug-in initialization. However, you can retrieve this value at run time through the managed programming model (EnableHTMLAccess property) or through the unmanaged programming model (EnableHtmlAccess property).

The following table lists the parameters that can be defined as Silverlight plug-in initialization events.

Parameter

Description

onError

Invoked when an error is generated in the Silverlight run-time components, either natively or in user code. See OnError.

onLoad

Invoked when the plug-in is successfully instantiated and all Silverlight content is loaded (everything referenced by the root XAML is parsed and has generated an object tree. See OnLoad.

The Silverlight.js file contains a Silverlight runtime version-checking method, IsInstalled, that you can use to verify whether a specified Silverlight run-time version is available before attempting to initialize a Silverlight control with calls to CreateObject or CreateObjectEx. IsInstalled returns true if the specified version matches or is compatible with the current version of the Silverlight runtime; otherwise, it returns false. The following HTML example shows how to invoke the IsInstalled method.

<div id="pluginHost" >
  <script type="text/javascript">

    // Determine whether the specified Silverlight runtime version is installed.
    var version = "3.0"; //deliberate over-version, will fail
    var isInstalled = Silverlight.isInstalled(version);

    
    // Create the plug-in if the specified Silverlight runtime version is installed.
    if (isInstalled)
    {
        var parentElement = document.getElementById("pluginHost");
        createSilverlight();
    }
    else
    {
        alert("Silverlight runtime version " + version + " not installed.");
    }
  </script>
</div>

Creating and Referencing Inline XAML

You can specify a source value that references XAML that is defined inline in the HTML. However, this is only supported when using the Silverlight unmanaged JavaScript programming model. See Using Inline XAML (Silverlight 2).

User-defined Initialization Parameters

During initialization, you can pass a custom parameter in string form that carries information that is relevant for that particular Silverlight plug-in instance. In Silverlight.js CreateObject or CreateObjectEx function calls, you pass this string as the initParams parameter. For more information about specifying the initialization parameters during instantiation and then using the values at run time, see Specifying and Retrieving Custom Initialization Parameters (Silverlight 2).

OnLoad is a convenient event that enables you to perform any last-minute operations before the Silverlight plug-in's content is presented to the user on the HTML page. You specify the OnLoad handler as part of the plug-in initialization, but you can script to the Silverlight programming model from within that handler, scripting against the object tree that exists after all the contained Silverlight content is loaded.

About the Silverlight OnLoad Event

The OnLoad event occurs after the XAML content in the Microsoft Silverlight plug-in has completely loaded. The onLoad parameter specifies by name the event-handler function that is called in response to the OnLoad event. onLoad is one of two possible events that you specify handlers for as part of Silverlight plug-in instantiation (the other event is onError). The OnLoad event occurs after any and all Loaded events occur in the Silverlight programming model (these events fire in inverse nesting order of the XAML, which is how XAML processors create and load content). The read-only IsLoaded property, which is set before the OnLoad event occurs, indicates whether the Silverlight plug-in is loaded.

OnLoad is potentially a useful event-handling entry point, because you are assured that the user interface (UI) defined in the source XAML for the Silverlight plug-in where the event is handled is ready for interaction and that all properties and methods are available. However, when using the Silverlight managed programming model, handling OnLoad might be less useful, because most of your post-load interaction will be done in managed code for the application, not in unmanaged JavaScript that is acting in the hosting browser. There are still some relevant scenarios for handling OnLoad, however, for example interacting with HTML DOM variables or HTML elements that you intend to access with HTML bridge APIs.

One aspect of the Silverlight plug-in is not determined at the time of OnLoad: the size of the overall plug-in content area, which is controlled by the hosting browser. If you need the current height and width of the overall content area, you should instead handle the Resized event (or OnResize in the unmanaged JavaScript programming model). This is true even for the initial load of the page that contains the Silverlight plug-in instance. Subsequent resizes of the OBJECT/EMBED tag, as initiated either by user action or through scripting to the hosting HTML element or the OBJECT/EMBED tags in the Document Object Model (DOM), also raise Resized if the size changes.

In the overall range of possible programming models, there are also JavaScript HTML DOM level events, including the HTML page's onload event. You can use the Silverlight plug-in OnLoad event and the HTML DOM onload event on the same page. In this case, the plug-in OnLoad event occurs before the HTML DOM onload event.

The context parameter is a user-defined unique identifier that can be passed as a parameter to an OnLoad event handler that can be shared by multiple Silverlight plug-ins on the same Web page. The OnLoad context parameter corresponds to the value of the context initialization parameter.

The Silverlight.js helper file generates a slightly different OnLoad event signature from the plug-in defined form that is provided to the OBJECT or EMBED tags created by the instantiation scripts. The Silverlight.js implementation of OnLoad wraps the basic OBJECT/EMBED OnLoad. If several plug-in instances are hosted on an HTML page, there is potential for event handlers to be confused about which instance was loaded. The CreateObject and CreateObjectEx functions in Silverlight.js add an optional context parameter for initialization. Typically, this parameter is set to a unique string. That context value is passed back as an event-handler parameter, which makes it much simpler to write common onLoad handler logic that can detect which plug-in instance's onLoad event is being handled at that time. Also, sender for event handlers references the specific Silverlight plug-in instance itself rather than an indirect HTML DOM reference.

The following HTML example shows how to define two Silverlight plug-in host elements on the same Web page.

<div id="pluginHost" >
  <script type="text/javascript">

    // Create a variable that references the HTML element that hosts the plug-in.
    var parentElement = document.getElementById("pluginHost");

    // Create variables that contain unique identifiers for the plug-in.
    var name = "myslPlugin_1";
    var context = "context_1";

    // Initialize and create the plug-in.
    createSilverlight();
  </script>
</div>

<div id="pluginHost2" >
  <script type="text/javascript">

    // Create a variable that references the HTML element that hosts the plug-in.
    var parentElement = document.getElementById("pluginHost2");

    // Create variables that contain unique identifiers for the instance.
    var name = "myslPlugin_2";
    var context = "context_2";

    // Initialize and create the plug-in.
    createSilverlight();

  </script>
</div>

The following JavaScript example shows the corresponding user-defined CreateSilverlight method. Notice that the CreateSilverlight method uses the inline-defined values of the parentElement, name, and context variables and passes these to CreateObject.

JScript
function createSilverlight()
{  
    Silverlight.createObject(
        "package.xap",                  // Source property value.
        parentElement,                  // DOM reference to hosting DIV tag.
        name,                           // Unique plug-in ID value, a variable set before each page call.
        {                               // Plug-in properties.
            width:'600',                // Width of rectangular region of plug-in, in pixels.
            height:'200',               // Height of rectangular region of plug-in, in pixels.
            version:'2.0'               // Plug-in version to use.
        },
        {
            onError:null,               // Use default error handler.
            onLoad:onLoad               // OnLoad event handler that can be used for multiple instances.
        },
        null,                           // InitParams property value set to null.  
        context);                       // Unique context ID, a variable set before each page call.
}

The following JavaScript example shows the corresponding OnLoad event-handling function that is used by both plug-in instances. The context parameter corresponds to the value defined by the plug-in's context initialization parameter.

JScript
function onLoad(plugin, userContext, sender)
{
    alert(plugin.id + " : " + userContext + " : " + sender.toString());
}
© 2008 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Page view tracker