WebBrowser::InvokeScript Method (String^)

 

Executes a script function that is implemented by the currently loaded document.

Namespace:   System.Windows.Controls
Assembly:  PresentationFramework (in PresentationFramework.dll)

public:
Object^ InvokeScript(
	String^ scriptName
)

Parameters

scriptName
Type: System::String^

The name of the script function to execute.

Return Value

Type: System::Object^

The object returned by the Active Scripting call.

Exception Condition
ObjectDisposedException

The WebBrowser instance is no longer valid.

InvalidOperationException

A reference to the underlying native WebBrowser could not be retrieved.

COMException

The script function does not exist.

InvokeScript(String^) should not be called before the document that implements it has finished loading. You can detect when a document has finished loading by handling the LoadCompleted event.

The following example shows how to call a script function in a document from a WPF application by using InvokeScript(String^). In this example, the script function has no parameters.

The following is the HTML document that implements the script function that will be called from WPF.

<html>
    <head>
        <script type="text/javascript">
            // Function Without Parameters
            function JavaScriptFunctionWithoutParameters()  
            {
              outputID.innerHTML = "JavaScript function called!";
            }
        </script>
    </head>
    <body>
    <div id="outputID" style="color:Red; font-size:16">
        Hello from HTML document with script!
    </div>
    </body>
</html>

The following shows the WPF implementation to call the script function in the HTML document.

private void callScriptFunctionNoParamButton_Click(object sender, RoutedEventArgs e)
{
  // Make sure the HTML document has loaded before attempting to
  // invoke script of the document page. You could set loadCompleted
  // to true when the LoadCompleted event on the WebBrowser fires.
  if (this.loadCompleted)
  {
    try
    {
      this.webBrowser.InvokeScript("JavaScriptFunctionWithoutParameters");
    }
    catch (Exception ex)
    {
      string msg = "Could not call script: " +
                   ex.Message +
                  "\n\nPlease click the 'Load HTML Document with Script' button to load.";
      MessageBox.Show(msg);
    }
  }
}

.NET Framework
Available since 3.0
Silverlight
Available since 4.0
Return to top
Show: