问题
How make window.history.go(-1) from c# code on Blazor?
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.
But it work from cshtml:
<button id="BtnBack" type="button" onclick="window.history.go(-1)" class="btn btn-default">Back</button>
回答1:
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>
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);
}
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.
来源:https://stackoverflow.com/questions/53911289/how-make-window-history-go-1-from-blazor-c-sharp-code