GVKun编程网logo

Silverlight和浏览器交互介绍----Silverlight中使用托管代码调用JavaScript(silverlight 浏览器)

10

如果您对Silverlight和浏览器交互介绍----Silverlight中使用托管代码调用JavaScript感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Silver

如果您对Silverlight和浏览器交互介绍----Silverlight中使用托管代码调用JavaScript感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于Silverlight和浏览器交互介绍----Silverlight中使用托管代码调用JavaScript的详细内容,我们还将为您解答silverlight 浏览器的相关问题,并且为您提供关于HttpClient能与silverlight交互么,如果不行,有什么技术可以模拟浏览器向silverlight交互、Javascript创建Silverlight Plugin以及自定义nonSilverlight和lowSilverlight样式_javascript技巧、Silverlight 2学习教程(五):JavaScript与Silverlight托管代码相互调用、Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象的有价值信息。

本文目录一览:

Silverlight和浏览器交互介绍----Silverlight中使用托管代码调用JavaScript(silverlight 浏览器)

Silverlight和浏览器交互介绍----Silverlight中使用托管代码调用JavaScript(silverlight 浏览器)

                                 Silverlight中使用托管代码调用JavaScript

(7)    Sliverlight和Javascript交互

1)      使用托管代码调用Javascript

a)      直接调用HtmlWindow对象的Alert和Confirm对象

b)      使用GetProperty方法调用Javascript代码

<script  type=”text/javascript”>

     Function myScriptMethod(a,b)

     {

               Var  resultDiv = $get(“result”);

               resultDiv.innerText = “A: ”+a+ “,B: ”+b;

}

</script>

ScriptObject sObj = HtmlWindow.GetProperty(“myScriptMethod”) as ScriptObject;

sObj.InvokeSelf(a,b);

c)       使用CreateInstance方法调用Javascript代码

<script  type=”text/javascript”>

     myScriptType = function(x,y)

     {

               This.X = x;

               This.Y = y;

}

myScriptType .prototype

     {

               display function()

               {

                        Var  resultDiv = $get(“result”);

                        resultDiv.innerText = “A: ”+a+ “,B: ”+b;

}        

}

</script>

ScriptObject  sObj = HtmlWindow.CreateInstance(“myScriptType”,a,b);

sObj.Invoke(“display”);

d)      使用Eval方法

使用Eval方法直接运行一段Javascript脚本,实际上就是将一段Javascript代码,直接提交到浏览器的Javascript引擎运行。

String  javaScriptStr = $get(“result”).innerText = “A: ”+a+ “,B: ”+b;

HtmlWindow.Eval(javaScriptStr);

e)      调用JavaScript中的Json对象

<script  type=”text/javascript”>

     Var Person = {Name:’Chris Meng’,Age:’26’};

Function myPerson()

     {

               Return Person;

}

</script>

Public class Person

{

     Public string Name{get;set;}

     Public int Age{get;set;}

}

ScriptObject  sObj = HtmlWindow.Invoke(“myPerson”,null) as ScriptObject;

Person person = sObj.ConvertTo<Person>();

即可得到前台的Javascript的信息。

HttpClient能与silverlight交互么,如果不行,有什么技术可以模拟浏览器向silverlight交互

HttpClient能与silverlight交互么,如果不行,有什么技术可以模拟浏览器向silverlight交互

HttpClient能与silverlight交互么,如果不行,有什么技术可以模拟浏览器向silverlight交互

Javascript创建Silverlight Plugin以及自定义nonSilverlight和lowSilverlight样式_javascript技巧

Javascript创建Silverlight Plugin以及自定义nonSilverlight和lowSilverlight样式_javascript技巧

默认情况下,生成的页面代码可能与下面的代码类似:

复制代码 代码如下:




IRERTranscript














Get Microsoft Silverlight






  我们可以给object对象传递不同的参数,如xap包的加载地址,onLoad或onError事件句柄,背景色,最小版本号支持等等,完整的参数信息读者可以参考Silverlight 3中param参数列表汇总。object对象中一般会包含一段标记,是用来显示当客户端浏览器未安装Silverlight插件时要显示的内容的,我们可以自定义其中的内容,如:
复制代码 代码如下:







Javascript创建Silverlight Plugin以及自定义nonSilverlight和lowSilverlight样式_javascript技巧





  当客户端浏览器未安装Silverlight插件时,程序会在相应的区域显示一张带有热区的图片,热区指向的位置是Microsoft提供的Silverlight安装地址。理论上,你可以指定任何的自定义代码来显示nonSilverlight的效果,但是Silverlight默认没有提供低版本Silverlight情况下要显示的效果,也就是lowSilverlight的情况。
Silverlight可以自动实现向前兼容,也就是在低版本下编译的Silverlight包可以在高版本下运行,相反,在高版本下编译的Silverlight包不能再低版本下运行,此时Silverlight插件会显示一张默认的图片用来告知用户升级插件,并弹出一个提示框,如下图:

Javascript创建Silverlight Plugin以及自定义nonSilverlight和lowSilverlight样式_javascript技巧

 

Javascript创建Silverlight Plugin以及自定义nonSilverlight和lowSilverlight样式_javascript技巧

 

  个人觉得这种用户体验并非很好,试想,如果当前页面上有多个Silverlight插件,岂不是要弹出多个提示框吗?那么如何来解决这个问题呢?事实上,我们除了直接在页面上添加object标记来呈现Silverlight外,还可以通过javascript脚本来动态添加Silverlight。Silverlight.js脚本为我们提供了一系列可用的方法,详细内容大家可以参考下msdn http://msdn.microsoft.com/zh-cn/library/cc838126(v=VS.95).aspx#isinstalled

  以及如何通过脚本在页面上添加Silverlight,http://msdn.microsoft.com/zh-cn/library/cc265155(v=VS.95).aspx

  msdn上给出了非常详细的例子来告诉我们如何使用这些脚本方法,有一点需要注意,使用Silverlight.js文件时一定要与当前Silverlight版本相一致,否则可能会有脚本错误,对应的Silverlight.js文件可以在微软的站点上下载,你会发现其实有很多个可用的版本,其中还包括支持调试的版本哦。

  createObject方法参数在使用的时候有几个问题需要注意下:

  1. 参数按顺序指定,如果有不需要传递的参数可用null代替。

  2. parent element参数必须指定,也就是object标记的父元素,可直接将元素的id当做对象传入,但是在Firefox中不支持,此时可以使用document.getElementById(''elementId'')语句代替该参数即可。

  3. param列表通过数组传递,参数名称与在object标记中使用的名称保持一致即可。

  4. 事件列表如果没有对应的页面脚本则传null值,否则会报脚本错误。

  5. 最后一个参数context如果不需要可以省去,不用传null或空值。

  你应该注意到了,在使用createObject方法时我们可以顺便给Silverlight指定nonSilverlight效果,这个是通过param列表中的altHtml参数来指定的,实施上,我们在页面上直接使用object标记呈现Silverlight时也可以使用alt属性来指定nonSilverlight效果,这个与在object标记中直接插入html代码的效果相同。
通过使用createObject方法,我们完全可以自定义lowSilverlight效果了,下面是一个例子:

复制代码 代码如下:






  使用Silverlight.isInstalled()方法可以判断客户端浏览器是否已经安装了指定版本的Silverlight插件,如果已经安装了,则使用Silverlight.createObject方法创建Silverlight对象,否则输出自定义的内容。

这里还有一篇文章个人觉得很有用,给大家分享下吧!

http://www.itstrike.cn/Question/Use-JavaScript-to-create-Silverlight-Object-createObject

Silverlight 2学习教程(五):JavaScript与Silverlight托管代码相互调用

Silverlight 2学习教程(五):JavaScript与Silverlight托管代码相互调用

要实现JavaScript调用Silverlight程序里面的托管代码,需要先在应用程序的启动(Application_Startup)事件里注册要进行访问的对象,而要从Silverlight的托管代码里访问HTML页面对象或者页面中的JavaScript,使用HtmlPageDocument/HtmlElementHtmlWindow即可。

下面,我们就以例子来说明两者相互访问的方法,代码里面有很详细的注释,这里不再累述。


Page.xaml

<UserControl x:Class="SilverlightApplication1.Page"
    xmlns="http://schemas.microsoft.com/client/2007" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Canvas Canvas.Top="20">
            <TextBlock Canvas.Top="10" Canvas.Left="20">请输入您的姓名: </TextBlock>
            <TextBox x:Name="UserInput" Width="200" Height="30" Canvas.Top="40" Canvas.Left="20"></TextBox>
            <TextBlock x:Name="Msg" Canvas.Top="90" Canvas.Left="20" Foreground="Navy" FontSize="36"></TextBlock>
            <Button Click="Button_Click" Content="单击我" FontSize="24" Width="160" Height="60" x:Name="BtnTest" Canvas.Top="160" Canvas.Left="20"></Button>
        </Canvas>
    </Grid>
</UserControl>

Page.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.browser;

namespace SilverlightApplication1
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string UserInputContent = this.UserInput.Text;
            if (UserInputContent.Equals(String.Empty))
            {
                UserInputContent = "Hello Silverlight World!";
            }
            else
            {
                UserInputContent = "你好," + UserInputContent;
            }
            HtmlWindow win = HtmlPage.Window;
            this.Msg.Text = UserInputContent;
            win.Alert("Silverlight 里面弹出的对话框。 " + UserInputContent);
            //执行页面中的js函数:
            win.Eval("getArraytest()");
            Object[] args = { "将此参数传递给 js 函数" };
            win.Invoke("getArrayTest", args);
            //如果页面中的值
            HtmlDocument doc = HtmlPage.Document;
            doc.GetElementById("UserName").SetAttribute("value", this.UserInput.Text);
        }

        [ScriptableMember()]
        public string InterInvole()
        {
            string username = HtmlPage.Document.GetElementById("UserName").GetAttribute("value");
            this.UserInput.Text = username;
            this.Msg.Text = "您输入了:" + username; 
            return "你从js脚本中调用了 Silverlight 里面的方法。";
        }
    }
}


App.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.browser;

namespace SilverlightApplication1
{
    public partial class App : Application
    {

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // Load the main control           
            Page p = new Page();
            HtmlPage.RegisterScriptableObject("SilverlightApplicationExample", p);

            // 请注意这里的定义方法,如果这里的p写成 new Page(),则Javascript基本不能给 UserInput 赋值!
            this.RootVisual = p;
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {

        }
    }
}

SilverlightApplication1TestPage.aspx

<%@ Page Language="C#" 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 xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Silverlight 2托管代码与Javascript交互的例子</title>
 <script type="text/javascript">
 //<!{CDATA[
 //定义全局变量:
 var testvar = "孟宪会";
 
 //定义全局函数:
 function getArraytest()
 {
  if(arguments.length > 0)
  {
   alert("js 对话框:您传递了参数。" + arguments[0]);
   return  arguments[0];
  }
  else
  {
   alert("js 对话框:无参数调用。");
   return "js 函数返回值";
  }
 } 
 
function SetUserName()
{
  alert(SilverlightPlugin.Content.SilverlightApplicationExample.InterInvole());
}

//定义Silverlight插件对象
var SilverlightPlugin = null;;
function pluginLoaded(sender)
{
   SilverlightPlugin = sender.get_element();  
}
 //]]>
 </script>
</head>
<body style="height: 100%; margin: 0;">
 <form id="form1" runat="server">
 <div style="border: 2px solid #EEE; margin: 20px;padding:20px">
  请输入你的名字:<input id="UserName" type="text" value="" />
  <input type="button" onclick="SetUserName()" value="将名字传递到 Silverlight" />
 </div>
 <br />
 <div style="border: 2px solid #EEE;margin: 20px;">
  <asp:ScriptManager ID="ScriptManager1" runat="server">
  </asp:ScriptManager>
  <asp:Silverlight ID="Xaml1" runat="server" OnPluginLoaded="pluginLoaded" Source="~/ClientBin/SilverlightApplication1.xap" Version="2.0" Width="400px" Height="300px" />
 </div>
 </form>
</body>
</html>

 

运行结果:

Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象

Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象

 

在上一篇Blog文章中,讲述了JavaScriptSilverlight托管代码相互调用的一些方法。实际上,HtmlWindowGetProperty方法和Invoke/InvokeSelf方法的返回值是Object类型的,代表 DOM对象或者JavaScript对象(HtmlDocumentHtmlElementHtmlObjectScriptObject)的返回值自动作为最接近的类型进行返回,但是,程序开发人员仍然需要明确地将该对象转换成相应的类型。所有的数字,由于跨浏览器的原因,都作为Double类型返回,如果需要Int32类型,则执行Convert.ToInt32()方法即可。

在现代的Web应用中,JSON的使用越来越频繁。Silverlight 2中要调用JavaScript中的JSON对象,首先在托管代码中声明一个类,类的属性与JSON对象的属性一致(不必完全一致),然后在托管代码中将ScriptObject对象转换成声明的这个类型即可。

下面是一个完整的例子:

Page.xaml

<UserControl x:Class="SilverlightApplication1.Page"
    xmlns="http://schemas.microsoft.com/client/2007" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="600" Height="480">
    <Grid x:Name="LayoutRoot" Background="White">
        <Canvas Canvas.Top="20">
            <TextBlock Canvas.Top="10" Canvas.Left="20">请输入您的姓名: </TextBlock>
            <TextBox x:Name="UserInput" Width="200" Height="30" Canvas.Top="40" Canvas.Left="20"></TextBox>
            <TextBlock x:Name="Msg" Canvas.Top="90" Canvas.Left="20" Foreground="Navy" FontSize="18" Width="500"></TextBlock>
            <Button Click="Button_Click" Content="单击我" FontSize="24" Width="160" Height="60" x:Name="BtnTest" Canvas.Top="160" Canvas.Left="20"></Button>
            <Button Click="JSONButton_Click" Content="JavaScript JSON 对象测试" FontSize="24" Width="300" Height="50" Canvas.Top="240" Canvas.Left="20"></Button>
            <TextBlock x:Name="Msg2" Canvas.Top="300" Canvas.Left="20" Foreground="Navy" FontSize="18" Width="500"></TextBlock>
            <TextBlock x:Name="Msg3" Canvas.Top="320" Canvas.Left="20" Foreground="Navy" FontSize="18" Width="500"></TextBlock>
        </Canvas>
    </Grid>
</UserControl>

Page.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.browser;
using System.Runtime.Serialization.Json;

namespace SilverlightApplication1
{
    public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string UserInputContent = this.UserInput.Text;
            if (UserInputContent.Equals(String.Empty))
            {
                UserInputContent = "Hello Silverlight World!";
            }
            else
            {
                UserInputContent = "你好," + UserInputContent;
            }
            HtmlWindow win = HtmlPage.Window;
            this.Msg.Text = UserInputContent;
            win.Alert("Silverlight 里面弹出的对话框。 " + UserInputContent);
            //执行页面中的js函数:
            win.Eval("getArraytest()");
            Object[] args = { "将此参数传递给 js 函数" };
            win.Invoke("getArrayTest", args);
         
            //如果页面中的值
            HtmlDocument doc = HtmlPage.Document;
            doc.GetElementById("UserName").SetAttribute("value", this.UserInput.Text);          
        }
        
        [ScriptableMember()]
        public string InterInvole()
        {
            string username = HtmlPage.Document.GetElementById("UserName").GetAttribute("value");
            this.UserInput.Text = username;
            this.Msg.Text = "您输入了:" + username; 
            return "你从js脚本中调用了 Silverlight 里面的方法。";
        }

        private void JSONButton_Click(object sender, RoutedEventArgs e)
        {
            ScriptObject so = HtmlPage.Window.Invoke("ReturnObject", nullas ScriptObject;
            Staple s = so.ConvertTo<Staple>();
            this.Msg2.Text = "大家好,我在  JavaScript JSON 对象中的名称是:" +  s.UserName;            
        }

        //接受Html页面传递的 JSON 字符串
        [ScriptableMember()]
        public void ReveiveJSON(string jsonString)
        {
            //注意引用:System.Runtime.Serialization.Json

            DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(Staple));
            System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.Unicode.GetBytes(jsonString));
            Staple staple = new Staple();
            staple = (Staple)json.Readobject(ms);
            Msg3.Text = "UserId = " + staple.UserId.ToString() + "  UserName = " + staple.UserName;
        }
    }

    public class Staple
    {
        public string UserName { setget; }
        public Double UserId { setget; }       
    }
}

App.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.browser;

namespace SilverlightApplication1
{
    public partial class App : Application
    {

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // Load the main control           
            Page p = new Page();
            HtmlPage.RegisterScriptableObject("SilverlightApplicationExample", p);

            // 请注意这里的定义方法,如果这里的p写成 new Page(),则Javascript基本不能给 UserInput 赋值!
            this.RootVisual = p;
        }

        private void Application_Exit(object sender, EventArgs e)
        {

        }
        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {

        }
    }
}

SilverlightApplication1TestPage.aspx

<%@ Page Language="C#" 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 xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Silverlight 2托管代码与Javascript交互的例子</title>
 <script type="text/javascript">
 //<!{CDATA[
 //定义全局变量:
 var testvar = "孟宪会";
 
 //定义全局函数:
 function getArraytest()
 {
  if(arguments.length > 0)
  {
   alert("js 对话框:您传递了参数。" + arguments[0]);
   return  arguments[0];
  }
  else
  {
   alert("js 对话框:无参数调用。");
   return "js 函数返回值";
  }
 } 
 
function SetUserName()
{
  alert(SilverlightPlugin.Content.SilverlightApplicationExample.InterInvole());
}


 var Staple = {
               UserId:100,
               UserName:'孟宪会',
               SayHello:function(){alert(this.UserName)}
               };
               
function ReturnObject()
{
  return Staple;
}

function SendJSONToSilverlight()
{
  SilverlightPlugin.Content.SilverlightApplicationExample.ReveiveJSON(JSON.stringify(Staple));
}

//定义Silverlight插件对象
var SilverlightPlugin = null;;
function pluginLoaded(sender)
{
   SilverlightPlugin = sender.get_element();  
}
 //]]>
 </script>
 <script src="json2.js" type="text/javascript"></script>
 <!-- http://www.JSON.org/json2.js -->
</head>
<body style="height: 100%; margin: 0;">
 <form id="form1" runat="server">
 <div style="border: 2px solid #EEE; margin: 20px;padding:20px">
  请输入你的名字:<input id="UserName" type="text" value="" />
  <input type="button" onclick="SetUserName()" value="将名字传递到 Silverlight" /> <input type="button" onclick="SendJSONToSilverlight()" value="JSON传递到 Silverlight" /> 
 </div>
 <br />
 <div style="border: 2px solid #EEE;margin: 20px;">
  <asp:ScriptManager ID="ScriptManager1" runat="server">
  </asp:ScriptManager>
  <asp:Silverlight ID="Xaml1" runat="server" OnPluginLoaded="pluginLoaded" Source="~/ClientBin/SilverlightApplication1.xap" Version="2.0" Width="600px" Height="480px" />
 </div>
 </form>
</body>
</html>

单击“JavaScript JSON 对象测试按钮,运行结果如下:

我们今天的关于Silverlight和浏览器交互介绍----Silverlight中使用托管代码调用JavaScriptsilverlight 浏览器的分享已经告一段落,感谢您的关注,如果您想了解更多关于HttpClient能与silverlight交互么,如果不行,有什么技术可以模拟浏览器向silverlight交互、Javascript创建Silverlight Plugin以及自定义nonSilverlight和lowSilverlight样式_javascript技巧、Silverlight 2学习教程(五):JavaScript与Silverlight托管代码相互调用、Silverlight 2学习教程(六): Silverlight托管代码调用Javascript中的JSON对象的相关信息,请在本站查询。

本文标签:

上一篇Silverlight和浏览器交互介绍-------JavaScript调用托管代码(silverlight 浏览器)

下一篇Silverlight访问Java Webservice策略文件安放位置(javaweb项目访问路径)