0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Blazor WebAssembly C#からJavaScriptを実行

Posted at

#はじめに
この記事ではC#からJavaScriptを実行するまでの記事です。JavaScriptからC#コードを呼ぶ事も出来ますが別記事で記載します。

#JavaScriptコードサンプル
サンプルとしてメッセージ表示系の以下のコードをwwwrootの中に入れています。

//アラート
export function displayAlert(message) {
    alert(message);
}

//Ok,キャンセルアラート
export function okCancelAlert(message) {
    return confirm(message);
}

//入力アラート
export function inputAlert(message, def) {
    return prompt(message, def);
}

#使い方

IJSRuntimeをInjectし、JSファイルを設定。 後は、JSの関数を指定して実行出来ます。

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />


@code{ 
    [Inject]
    private IJSRuntime JSRuntime { get; set; }
    private IJSObjectReference JSCommand { get; set; }

    protected override async Task OnInitializedAsync()
    {
        this.JSCommand = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./JsCommand.js");

        await this.JSCommand.InvokeVoidAsync("displayAlert", "メッセージを表示");

        var result = await this.JSCommand.InvokeAsync<bool>("okCancelAlert", "Ok,Cancelメッセージを表示");

        await this.JSCommand.InvokeVoidAsync("displayAlert", result);
    }

}

#動作
11.gif

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?