Compartilhar via


CoreWebView2Frame.ExecuteScriptAsync(String) Method

Definition

Runs JavaScript code from the javaScript parameter in the current frame.

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

Returns

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

Examples

string iframesData = WebViewFrames_ToString();
string iframesInfo = "Enter iframe to run the JavaScript code in.\r\nAvailable iframes: " + iframesData;
var dialogIFrames = new TextInputDialog(
    title: "Inject Script Into IFrame",
    description: iframesInfo,
    defaultInput: "0");
if (dialogIFrames.ShowDialog() == true)
{
    int iframeNumber = -1;
    try
    {
        iframeNumber = Int32.Parse(dialogIFrames.Input.Text);
    }
    catch (FormatException)
    {
        Console.WriteLine("Can not convert " + dialogIFrames.Input.Text + " to int");
    }
    if (iframeNumber >= 0 && iframeNumber < _webViewFrames.Count)
    {
        var dialog = new TextInputDialog(
            title: "Inject Script",
            description: "Enter some JavaScript to be executed in the context of iframe " + dialogIFrames.Input.Text,
            defaultInput: "window.getComputedStyle(document.body).backgroundColor");
        if (dialog.ShowDialog() == true)
        {
            string scriptResult = await _webViewFrames[iframeNumber].ExecuteScriptAsync(dialog.Input.Text);
            MessageBox.Show(this, scriptResult, "Script Result");
        }
    }
}

Remarks

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 before ContentLoading, the script will not be executed and the JSON null will be returned. This operation works even if IsScriptEnabled is set to false.

Applies to