如何从Blazor C#代码制作window.history.go(-1)? [英] How make window.history.go(-1) from Blazor c# code?
问题描述
如何在Blazor上使用c#代码制作window.history.go(-1)?
How make window.history.go(-1) from c# code on Blazor?
我尝试使用JSRuntime.Current.InvokeAsync
I tried to use JSRuntime.Current.InvokeAsync
JSRuntime.Current.InvokeAsync< string >( "history.go", new[] {-1} );
JSRuntime.Current.InvokeAsync< string >( "top.history.go", new[] {-1} );
JSRuntime.Current.InvokeAsync< string >( "window.history.go", new[] {-1} );
JSRuntime.Current.InvokeAsync< string >( "window.top.history.go", new[] {-1} );
但是我得到了错误:在未实现接口历史记录的对象上被调用.
but I get the error: go called on an object that does not implement interface History.
但是它可以通过cshtml进行工作:
But it work from cshtml:
<button id="BtnBack" type="button" onclick="window.history.go(-1)" class="btn btn-default">Back</button>
推荐答案
不确定细节,但我相信要像这样进行互操作,您需要对此进行更明确的说明.因此,如果您将此脚本放在您的index.html
中(而不是我建议您在生产中使用的地方):
Not sure the details, but I believe to do interop like this, you need to be a bit more explicit about it. So if you put this script in your index.html
(not where I'd necessarily recommend you put it in production):
<script>
window.test = {
historyGo(value) {
window.history.go(value);
}
};
</script>
然后将这段代码放在Blazor页面中:
Then put this code in your Blazor page:
<button type="button" onclick="@OnClick">Go Back</button>
具有这样的事件处理程序:
With an event handler like this:
private void OnClick()
{
JSRuntime.Current.InvokeAsync<object>("test.historyGo", -1);
}
一切正常.我尝试了您采用的方法(在您自己的JS中没有显式的互操作层),同样发现它不起作用.但这对我来说似乎是一个合理的解决方法.会对为什么 this 有效而您的代码无效的原因感兴趣,但是希望这会有所帮助.
Everything works as you'd expect. I tried the approach you took (without an explicit interop layer in your own JS) and likewise saw it did not work. But this seems a reasonable workaround to me. Would be interested in an elaboration for why this works and your code does not, but hopefully this is helpful.
这篇关于如何从Blazor C#代码制作window.history.go(-1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!