C#/Blazor

[Blazor] Copy Clipboard

kjun.kr 2023. 7. 27. 00:06
728x90
728x170

특정항목을 복사하기 위한 기능 Copy Clipboard 처리하는 방법입니다.

Services 폴더를 만들고 Class 를 하나 추가합니다.

ClipboardService.cs

using Microsoft.JSInterop;

namespace Blazor.ClipBoardTest.Services
{
    public class ClipboardService
    {
        private readonly IJSRuntime jsRuntime;

        public ClipboardService(IJSRuntime jsRuntime)
        {
            this.jsRuntime = jsRuntime;
        }

        public ValueTask<string> ReadTextAsync()
        {
            return jsRuntime.InvokeAsync<string>("navigator.clipboard.readText");
        }

        public ValueTask WriteTextAsync(string text)
        {
            return jsRuntime.InvokeVoidAsync("navigator.clipboard.writeText", text);
        }
    }
}

Program.cs 에 아래 코드를 추가합니다.

builder.Services.AddScoped<ClipboardService>();

using Blazor.ClipBoardTest.Services;

using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;

namespace Blazor.ClipBoardTest
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("#app");
            builder.RootComponents.Add<HeadOutlet>("head::after");

            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
            builder.Services.AddScoped<ClipboardService>();

            await builder.Build().RunAsync();
        }
    }
}

화면에서는 아래처럼 처리합니다.

Index.razor

@page "/"
@using Blazor.ClipBoardTest.Services;

@inject ClipboardService ClipboardService;
@inject IJSRuntime JSRuntime

<PageTitle>Copy Clipboard</PageTitle>

<p role="status">GUID: @guid</p>
<button class="btn btn-primary" @onclick="CreateGUID">Carete GUID</button>
<button class="btn btn-primary" @onclick="CopyTextToClipboard">Copy</button>

@code {
    private string guid = string.Empty;

    private void CreateGUID()
    {
        guid = Guid.NewGuid().ToString();
    }

    private async Task CopyTextToClipboard()
    {
        try
        {
            await ClipboardService.WriteTextAsync(guid);
        }
        catch(Exception ex)
        {
            Console.WriteLine("Clipboard Error " + ex.ToString());
        }
    }
}

실행결과

 

[Source]
https://github.com/kei-soft/Blazor.AppTest/tree/master/Blazor.ClipBoardTest

 

728x90
그리드형