问题
Does anybody know if it is possible to access and manipulate an element in the html page that is rendered by the Silverlight 4 WebBrowser control.
The scenario is like this. The user launches a Silverlight OOB application with elevated trust. The user manipulates some data in the application but must submit part of the data to an external web site. If I open the external site in a WebBrowser control, is there any way I can assist the user by pre filling some information in the external sites' web form via programmatic access to the DOM?
回答1:
Quick answer: No.
Long Answer: The original intent for the OOTB + WebBrowserControl was to help customers bake in both Rich Text Format displays (Email, RSS etc) and at the same time provide the ability for printing support for large documents to occur (reports etc).
The same rules apply for iframe as you have with this Control (as far as I know there isn't any plans to change this).
The scenario you just mentioned made me a little nervous as I can see a few of the guys on the Silverlight team raising the issue around security - in that this can be used as a way to automate DOS attacks on websites etc via Silverlight as the unsuspecting payload (even with elevated trust users are often duped into installing things like this - its the reality sorry)..
- Scott Barnes / Former Silverlight Product Manager.
回答2:
You can execute javascript functions inside the WebBrowser control using the InvokeScript method. Note that you can't make cross-domain calls.
Example:
Html page
<html ><head>
<script type="text/javascript">
function SetValues(val) {
document.getElementById("q").value = val;
}
</script>
</head><body>
<input type="text" id="q" />
</body></html>
Xaml
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="268*" />
<ColumnDefinition Width="132*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<WebBrowser Name="webBrowser1" Grid.Row="1" Grid.ColumnSpan="2" />
<Button Content="Search" Name="button1" Click="button1_Click"
Grid.Column="1" />
<TextBox Name="textBox1" />
</Grid>
code behind
public MainPage()
{
InitializeComponent();
webBrowser1.Navigate(new Uri("http://localhost:58976/HTMLPage1.htm"));
}
private void button1_Click(object sender, RoutedEventArgs e)
{
webBrowser1.InvokeScript("SetValues",textBox1.Text);
}
来源:https://stackoverflow.com/questions/2677536/silverlight-4-oob-application-access-html-dom-of-the-page-in-webbrowser-control