How make window.history.go(-1) from Blazor c# code?

本小妞迷上赌 提交于 2020-02-08 10:27:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!