Instantiating a Silverlight Plug-in (Using CreateSilverlight.js and Silverlight.js)

The Microsoft Silverlight plug-in defines the area in which the Silverlight-based application displays. You embed the plug-in within its host HTML page, and you can either position the plug-in somewhere inline in the HTML page display or you can have the plug-in take up the entire HTML page. You use a pair of JavaScript helper files, CreateSilverlight.js and Silverlight.js, to initialize and create Silverlight plug-ins on a Web page. Using the Silverlight.js file is the required technique for using Silverlight plug-ins in an application. The CreateSilverlight.js file is a convenience file that lets you package and provide specific parameters to the methods that are in Silverlight.js.

This topic contains the following sections:

The Silverlight Plug-in (in Context)

A typical Web page that has embedded Silverlight content includes a number of components, as shown in the following illustration.

Relationship between a Web page and Silverlight content

Instantiating a Silverlight Plug-in (Using CreateSilverlight.js and Silverlight.js)_第1张图片

  • Web page: The Web page that the Silverlight-based application is embedded (hosted) in.
  • HTML placeholder element: A block-level HTML element (usually a <DIV>) that contains the Silverlight plug-in and therefore determines where the Silverlight-based application is rendered on the Web page.
  • Silverlight plug-in: The component that renders the Silverlight content. This plug-in is defined in an HTML page by creating an OBJECT or EMBED tag and setting its parameter values. Functions in the Silverlight.js helper file produce this <OBJECT> or <EMBED> tag output (see Using JavaScript Helper Files to Create a Silverlight Plug-in section). You can access this plug-in and reference its properties, methods, and events at run time.
  • XAML Silverlight content: The XAML content that provides the presentation of your Silverlight-based application.

Note   Parts 1 and 2 of the Silverlight 1.0 QuickStart explain how to use these components.

To learn more about positioning the plug-in in your HTML page, see Silverlight Object Positioning.

Role of the Helper Files

CreateSilverlight.js and Silverlight.js are helper files that you use to create a Silverlight-based application. The following table lists the main roles of the files involved in initializing and creating a Silverlight plug-in.

File Description

Default.htmdefault.aspx, or other HTML file

Hosts the Silverlight plug-in by invoking the CreateSilverlight method that is defined in the CreateSilverlight.js file.

CreateSilverlight.js

Defines the CreateSilverlight method that invokes either the CreateObject or CreateObjectExmethod, both of which are defined in the Silverlight.js file.

Silverlight.js

Defines the CreateObject and CreateObjectEx methods, which provide version-checking support and generate the <OBJECT> or <EMBED> markup for plug-in instantiation in the HTML file that hosts the Silverlight plug-in.

The following illustration shows the relationships among these three files.

Relationship between Default.htm, CreateSilverlight.js, and Silverlight.js

Instantiating a Silverlight Plug-in (Using CreateSilverlight.js and Silverlight.js)_第2张图片

Calling the CreateSilverlight Method

To use a Silverlight plug-in on a Web page, you modify the page to include the following:

  1. Two <SCRIPT> tags that reference the location of CreateSilverlight.js and Silverlight.js.
  2. An HTML block element such as a <DIV> tag that hosts 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.
  3. A <SCRIPT> tag embedded within that block element that contains two lines of JavaScript. The first line creates a variable that references the HTML block element through the HTML Document Object Model (DOM) scripting call getElementByID. The second line invokes the CreateSilverlightmethod.

The following HTML example shows these three modifications to the Web page that hosts the Silverlight plug-in.

HTML
...
<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>
  <script type="text/javascript" src="js/CreateSilverlight.js"></script>

  <!-- Application event-handler functions -->
  <script type="text/javascript" src="js/eventhandlers.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.
      createSilverlight();
    </script>
  </div>
</body>
...

Modifying the CreateSilverlight Method

The CreateSilverlight.js file typically contains a single method, CreateSilverlight. The source code that defines this method contains two method invocations that are commented out: Silverlight.createObject and Silverlight.createObjectEx. You can use either of these methods to initialize and create the Silverlight plug-in. The only difference between the two methods is that Silverlight.createObjectEx uses a single JavaScript Object Notation (JSON) dictionary to package all of its parameters. The following JavaScript example shows a modified call to Silverlight.createObject.

JavaScript
function createSilverlight()
{  
    Silverlight.createObject(
        "plugin.xaml",                      // Source property value.
        parentElement,                      // DOM reference to hosting DIV 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.
            inplaceInstallPrompt:false,     // Determines whether to display in-place install prompt if invalid version is detected.
            background:'white',             // Background color of plug-in.
            isWindowless:'false',           // Determines whether to display plug-in in windowless mode.
            framerate:'24',                 // MaxFrameRate property value.
            version:'1.0'                   // Silverlight version.
        },
        {
            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.
}

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

JavaScript
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.
            inplaceInstallPrompt:false, // Determines whether to display in-place install prompt if invalid version is detected.
            background:'white',         // Background color of plug-in.
            isWindowless:'false',       // Determines whether to display plug-in in windowless mode.
            framerate:'24',             // MaxFrameRate property value.
            version:'1.0'},             // Silverlight version.
        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.
}

Parameter Values

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 object model, so you can retrieve the values of the initialization parameters in run-time code.

  • source -- Refers to the XAML content file, and corresponds to the Source property of the Silverlight plug-in.
  • parentElement -- Refers to the block element in the HTML file that contains the createSilverlight scripting call and becomes the host 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 the User-Defined Initialization Parameters section.
  • 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 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'swidth property. This property is exposed through the 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.
height Defines the height of the rectangular region that displays the Silverlight content. Sets the plug-in'sheight 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.
background Specifies the background color of the rectangular region that displays XAML content. This value can be retrieved and set at run time through the SilverlightObject.settings.Background property. See theBackground property for valid parameter settings for the background parameter. The default value is null, which is equivalent to the color white for this property.
isWindowless Determines whether the plug-in displays as a windowless plug-in. This value can be retrieved at run time through the SilverlightObject.settings.Windowless property. If the value is set to true and theBackground 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 property is ignored in run-time behavior.
frameRate Specifies the maximum number of frames to render per second. This value can be retrieved and set at run time through the SilverlightObject.settings.MaxFrameRate property. The actual frame rate that Silverlight content renders depends on system load performance. The maximum frame rate is 64. If the property is set to a value that is greater than 64, it is considered to be set to 64. The default value is 24.
inplaceInstallPrompt

Determines whether the in-place installation prompt appears if the specified version of the Silverlight plug-in is not installed. The default value is false, which means that the standard installation prompt appears. There is no corresponding run-time property. For more information, see Using the InplaceInstallPrompt Parameter.

Note   Do not place quotation marks around this Boolean value. Other Boolean values in the initialization (such as isWindowless) require quotation marks, but inplaceInstallPrompt will not be processed correctly if you use quotation marks.

version Specifies the Silverlight version required to run the application. The version initialization parameter is compared with the version of the currently installed Silverlight runtime. The inplaceInstallPromptparameter determines which installation dialog box appears when the version checking in Silverlight.js returns false. There is no corresponding run-time property.
ignoreBrowserVer

Determines whether to disable checking for supported Silverlight browsers and browser versions. Setting this initialization parameter to true means that any browser can attempt to display the Silverlight-based application. The default value is false, which means that only supported Silverlight browsers can display the application. There is no corresponding run-time property.

Note   Do not place quotation marks around this Boolean value. Other Boolean values in the initialization (such as isWindowless) require quotation marks, but ignoreBrowserVer will not be processed correctly if you use quotation marks.

enableHtmlAccess Not relevant for Silverlight 1.0. In Silverlight 1.0, the Silverlight object model always has access to the browser DOM. This parameter exists for use by Silverlight 1.1 Alpha versions. This value can be retrieved at run time through the SilverlightObject.settings.EnableHtmlAccess property. The default value is true.

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

Parameter Description
onError Specifies a user-defined JavaScript error-handling function that is invoked when an error is generated in the Silverlight run-time components. (See OnError.) The default value is the default error-handling function, "default_error_handler", which is defined in Silverlight.js.
onLoad Specifies the event-handling function for the OnLoad event. The default value is null.

Using the IsInstalled Method

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 CreateObjectExIsInstalled 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.

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

    // Determine whether the specified Silverlight runtime version is installed.
    var version = "2.0"; //deliberate over-version
    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>

Silverlight Versioning

The strings that communicate versions of the Silverlight plug-in use the following format:

versionMajor.versionMinor.buildNumber.revisionNumber

Generally speaking, the versions you pass in the CreateObject or IsInstalled function only need to specify versionMajor.versionMinor. The full build and revision numbers of the version of Silverlight that is installed may or may not match the numbers specified in the function parameter. If a more specific check succeeds, a less specific check must succeed as well. For example, if IsVersionSupported("1.0.01820.55") returns true, bothIsVersionSupported("1.0.01820") and IsVersionSupported("1.0") must return true. Conversely, if a less specific check fails, a more specific check must fail, too. For example, if IsVersionSupported("1.0") returns false, both IsVersionSupported("1.0.01820") andIsVersionSupported("1.0.01820.55") must return false.

Creating and Referencing Inline XAML

Instead of using a discrete file that is referenced by a Uniform Resource Identifier (URI) to set the initial Silverlight content, you can specify an area of inline HTML content that contains your XAML. To use this technique, you must enclose the XAML in a special <SCRIPT> block, and use a "#" prefix in the sourceparameter. For more information about this technique, see Using Inline XAML as the XAML Source.

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. This is particularly useful if your HTML page hosts multiple Silverlight plug-in instances, and attempting to hold that information in a single page-level JavaScript variable would be inconvenient. For more information about specifying the initialization parameters during instantiation and then using the values at run time,Specifying and Retrieving Custom Initialization Parameters.

Using the InplaceInstallPrompt Parameter

The inplaceInstallPrompt parameter is an initialization parameter that determines whether the in-place installation prompt appears if the specified version of the Silverlight plug-in is not installed. The default value is false, which means that if the version checking in Silverlight.js returns false, the following Silverlight standard installation dialog box will appear.

Silverlight standard installation dialog box

When you click the Silverlight standard installation dialog box, the Silverlight download page appears.

Setting the InplaceInstallPrompt Parameter to True

When inplaceInstallPrompt is set to true, the following in-place installation prompt appears if the specified version of the Silverlight plug-in is not installed.

Silverlight in-place installation dialog box

Instantiating a Silverlight Plug-in (Using CreateSilverlight.js and Silverlight.js)_第3张图片

When you click in the upper portion of the Silverlight in-place installation dialog box, the Silverlight download process begins. The lower portion of the in-place installation dialog box provides links to the Silverlight license agreement(s) and Silverlight privacy information. You must not alter Silverlight.js to change the wording, color, or location of the links, or remove these links from the in-place installation dialog box.

Note   All browsers that are supported by Silverlight, except for Internet Explorer on the Windows operating system, require the browser to be restarted before Silverlight will work properly. You should warn users on your Web site (not in the installation dialog box) that restarting their browser might be required.

Using the OnLoad Event

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 object model from within that handler, scripting against the object tree that exists after all the contained Silverlight content is loaded. For information about the OnLoad event and writing handlers for this event, see Writing Event Handlers for the OnLoad Event.

See Also

Silverlight Object Models and Scripting to the Silverlight Plug-In
Specifying and Retrieving Custom Initialization Parameters
Writing Event Handlers for the OnLoad Event
Localized Deployment
Overviews and How-to Topics

你可能感兴趣的:(silverlight)