在blazor中,我使用NavigationManager.NavigateTo(url)
来更改窗口位置,但是如何使用它来打开具有指定URL的新标签,而不必在OnAfterRenderAsync()
上调用JS
答案 0 :(得分:7)
截至2019年3月21日,目前无法直接使用纯Blazor直接执行此操作,您需要使用JSInterop。幸运的是,这很容易做到。在您的.razor
文件的顶部添加
@inject IJSRuntime JSRuntime;
然后像这样使用它
await JSRuntime.InvokeAsync<object>("open", url, "_blank");
答案 1 :(得分:2)
以前,此代码有效。
await _jsRuntime.InvokeVoidAsync("open", new object[2] { url, "_blank" });
目前,它导致未捕获的异常:
> "TypeError: Converting circular structure to JSON
我发现此行为在此处(https://github.com/dotnet/aspnetcore/issues/16632)进行了解释:
这是因为window.open返回一个WindowProxy对象(请参见 https://developer.mozilla.org/en-US/docs/Web/API/Window/open)。 WindowProxy不可JSON序列化,因此不能用作返回值 .NET代码的值。
要解决此问题,请不要直接调用window.open,而应调用JS 您自己的函数,不返回任何内容或返回某些内容 可以JSON序列化。
根据以上建议,我在index.html中添加了以下内容:
<script>
window.blazorOpen = (args) => {
window.open(args);
};
</script>
并修改了我的C#代码背后调用以传递窗口参数:
await _jsRuntime.InvokeVoidAsync("blazorOpen", new object[2] { url, "_blank" });
现在,我们通过丢弃window.open返回的WindowProxy对象来有效地避免了该问题,该对象先前已返回给InvokeVoidAsync,并且.NET尝试(未成功)处理。
答案 2 :(得分:0)
只需使用常规链接
<a href="@Url" target="_blank">@UrlDescription</a>
答案 3 :(得分:0)
使用时您将获得TypeError: Converting circular structure to JSON
await _jsRuntime.InvokeVoidAsync("open", new object[2] { url, "_blank" });
或
await _jsRuntime.InvokeAsync<object>("open", url, "_blank");
<块引用>
这是因为 window.open
返回一个 WindowProxy
对象(请参阅
https://developer.mozilla.org/en-US/docs/Web/API/Window/open)。
WindowProxy
不可 JSON 序列化,因此不能用作 .NET 代码的返回值。
取自见here。
为了不使用 javascript 函数解决这个问题,我使用以下内容
await JSRuntime.InvokeVoidAsync("eval", $"let _discard_ = open(`{url}`, `_blank`)");
答案 4 :(得分:0)
根据此处 API 的最新变化,您可以向 URL 添加任何自定义对象属性,如下所示:
/// <summary>
/// Show Link
/// </summary>
/// <returns></returns>
private async Task ShowLink()
{
if (this.selectedItem != null)
{
string url = $"https://example.com/sites/" + this.selectedItem.Id + "/SitePages/Reports/somepage.aspx";
//NavigationManager.NavigateTo(url, false);//opens the new page on same browser tab
string[] values = { url, "_blank" };
CancellationToken token = new CancellationToken(false);
await JSRuntime.InvokeAsync<object>("open", token, values);//opens the link in new browser tab
}
}