[Blazor] Blazor 에서 Javascript 호출 방법

728x90
반응형

학습도 할겸 해서 ASP.NET MVC 템플릿을 이용해서 제작되어 있는 기능을 Blazor로 옮기는 작업을 최근 진행하고 있었습니다.

RESTFul API를 호출 하고, 결과를 JSON으로 보여주는 부분을 Beautiful JSON Viewer Editor 라이브러리를 이용해서 보여주고 있었는데요.

https://www.jqueryscript.net/other/Beautiful-JSON-Viewer-Editor.html

 

Beautiful JSON Viewer And Editor With jQuery - JSON Editor

A lightweight, simple, beautiful JSON viewer and editor plugin helps the developers to render JSON objects in HTML with collapsible/expandable navigation just like a tree view.

www.jqueryscript.net

 

javascript 로딩과 관련해서 진행에 문제가 발생하였습니다.

razor 페이지 내에서, @section과 RenderSection은 적용되지 않았으며,

script 구문 또한 적용 할 수 없었습니다.

 

이 문제를 해결하려 고민 하던 중, 각 razor 페이지에서 javascript 문을 호출 해 줘야 하는 부분에 방법을 찾다가 알게된 내용을 공유 합니다.

 

 


 

문제상황

razor 페이지 내에서 @section 및 script 구문을 사용 할 수 없었으며, cshtml 파일에서도 @RenderSection을 사용 할 수 없었습니다. 

 

test.razor 페이지에서 @section 구문과 script를 사용하면, 아래와 같은 오류 메시지가 출력이 됩니다. 

test.razor 페이지

_Host.cshtml 페이지에서는 @RenderSection을 지원하지 않았습니다.

_Host.cshtml 페이지

 

 

Blazor의 경우 Components 외부에서만 Javascript를 추가 할 수 있고, Index.html / _Host.cshtml 에 추가 할 수 있었습니다.

 

 


 

해결 방법

  1. IJSRuntime 추상화를 사용해서 호출 할 수 있습니다. JS Interop 호출을 실행 하려면 구성요소에 IJSRuntime 추상화를 주입해야 합니다.
  2. 또한 JavaScript 함수에 대한 식별자를 사용하고, 전역범위인 window를 기준으로 합니다.
_Host.cshtml



<script src="js/Beautiful-JSON-Viewer-Editor/dist/jquery.json-editor.min.js"></script>
<script>
    window.PrettyJson = () => {
        $('pre').each(function () {
            try {
                var jsonData = $(this)[0].innerText;
                jsonData = jsonData.replace(/([\[:])?(\-)?(\d+)([,\}\]])/g, "$1\"$2$3\"$4");
                //console.log(jsonData)
                var editor = new JsonEditor($(this)[0], JSON.parse(jsonData))
            }
            catch (error) {
                console.log(error);
            }
        });
    };
</script>

window.PrettyJson 이라는 식별자를 사용하였고, 해당 함수는 "pre" 태그에 있는 텍스트를 JsonEditor 라이브러리를 이용해서 꾸며주는 기능을 합니다.

Blazor에서 호출 시 "PrettyJson" 이라는 식별자만 호출 하면 됩니다.

 

 

@inject IJSRuntime JS

...
...

@code {

...


...


    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
        }
        else
        {
            await JS.InvokeVoidAsync("PrettyJson");
        }
    }
}

상단에 IJSRuntime 추상화 클래스를 정의하고,

LifeCycle 를 이용해서 모든 구성요소가 로드 된 이후

OnAfterRenderAsync 에서 IJSRuntime 의 InvokeVoidAsync 메소드를 이용해서 PrettyJson 식별자를 호출하여 줍니다.

 

2021/01/22 - [ASP.NET Core Blazor] - [Blazor] ASP.NET Core Blazor 수명 주기

 

 

 

적용 전

 

적용 후

 

 

 

주 목적은  Beautiful JSON Viewer Editor 의 적용이였지만, Blazor 에서 Javascript 호출을 고민하셨던 분들이 계시다면, 유용하게 사용할 것 같습니다.

 

 

 

 

출처

https://docs.microsoft.com/ko-kr/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-5.0

 

ASP.NET Core Blazor의 .NET 메서드에서 JavaScript 함수 호출

Blazor 앱의 .NET 메서드에서 JavaScript 함수를 호출하는 방법을 알아봅니다.

docs.microsoft.com

 

 

 

 

728x90