Sdílet prostřednictvím


CoreWebView2.ExecuteScriptAsync(String) Method

Definition

Runs JavaScript code from the javaScript parameter in the current top-level document rendered in the WebView.

public System.Threading.Tasks.Task<string> ExecuteScriptAsync (string javaScript);
member this.ExecuteScriptAsync : string -> System.Threading.Tasks.Task<string>
Public Function ExecuteScriptAsync (javaScript As String) As Task(Of String)

Parameters

javaScript
String

The JavaScript code to be run in the current top-level document rendered in the WebView.

Returns

A JSON encoded string that represents the result of running the provided JavaScript.

Examples

var dialog = new TextInputDialog(
    title: "Inject Script",
    description: "Enter some JavaScript to be executed in the context of this page.",
    defaultInput: "window.getComputedStyle(document.body).backgroundColor");
if (dialog.ShowDialog() == true)
{
    string scriptResult = await _iWebView2.ExecuteScriptAsync(dialog.Input.Text);
    MessageBox.Show(this, scriptResult, "Script Result");
}

Remarks

If the result is undefined, contains a reference cycle, or otherwise is not able to be encoded into JSON, the JSON null value is returned as the "null" string.

A function that has no explicit return value returns undefined. If the script that was run throws an unhandled exception, then the result is also null. This method is applied asynchronously. If the method is run after the NavigationStarting event during a navigation, the script runs in the new document when loading it, around the time ContentLoading is run. This operation works even if IsScriptEnabled is set to false.

Applies to

See also