3

I would like to open a PDF in a new Tab. The following code works in a normal HTML File, but not in Blazor. Is there any way to use it in Blazor or is there another way to open a PDF in Blazor?

<a href="Path" target="_blank">Read more</a>
MaxB
  • 260
  • 2
  • 13

2 Answers2

0

What works in "normal" HTML, does not work in Blazor, because the service-worker routes unknown routes to index.html. See onFetch() method of service-worker.published.js:

const shouldServeIndexHtml = event.request.mode === 'navigate';
const request = shouldServeIndexHtml ? 'index.html' : event.request;

When you click your link <a href="Path" target="_blank">Read more</a>, the shouldServeIndexHtml is true.

To avoid this, simply change above code to

const shouldServeIndexHtml = event.request.mode === 'navigate'
     && !event.request.url.includes('/pdf/');
const request = shouldServeIndexHtml ? 'index.html' : event.request;

This assumes, that your pdfs are in a subfolder "pdf" under wwwroot. Please find more information here. Since the url includes "/pdf/", the shouldServeIndexHtml becomes false and your pdf is displayed.

Flippowitsch
  • 315
  • 3
  • 15
-2

Two options I can suggest:

Via a button.

@inject IJSRuntime jsRuntime

<button @onclick="@LoadPage">Load Page</button>

@code {
    async Task LoadPage()
    {
        await jsRuntime.InvokeAsync<object>("open", "MyPage", "_blank");
    }
}

Via a link.

<a class="dropdown-item" href="MyPage" target="_blank">

where the razor page you want to launch has the following at the top:

@page "/MyPage"
DarkIceDust
  • 231
  • 2
  • 14