WebView滚动内容

时间:2014-10-13 13:37:56

标签: javascript c# webview winrt-xaml windows-8.1

如何在WebView中设置页面滚动位置? 我通过在页面上添加JavaScript来获得X和Y coord:

window.onscroll = scroll;
function scroll () {"
window.external.notify(window.pageXOffset + \",\" + window.pageYOffset)"
}

并将X和y保存在数组中:

private void WebView_OnScriptNotify(object sender, NotifyEventArgs e)
        {
            string[] valuePair = e.Value.Split(',');
            XY[0] = int.Parse(valuePair[0]);
            XY[1] = int.Parse(valuePair[1]);
        }

但是当我加载页面并想要恢复滚动位置时,如何在WebView中滚动页面?

1 个答案:

答案 0 :(得分:2)

你大部分都在那里。离开页面时需要保存当前位置,然后在返回页面时导航回该位置。试试这个:

在MainPage.xaml.cs中:

    static Point ScrollPosition = new Point();

    private void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
    {
        string[] Coordinates = e.Value.Split(',');
        ScrollPosition.X = double.Parse(Coordinates[0]);
        ScrollPosition.Y = double.Parse(Coordinates[1]);
    }

    private async void MyWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
    {
        await MyWebView.InvokeScriptAsync("SetScrollPosition", new string[] { ScrollPosition.X.ToString(), ScrollPosition.Y.ToString() });
    }

在MainPage.xaml中:

  <WebView x:Name="MyWebView" Width="800" Height="500" Source="ms-appx-web:///HTMLPage1.html" ScriptNotify="MyWebView_ScriptNotify" NavigationCompleted="MyWebView_NavigationCompleted"/>

在HTMLPage1.html中:

  window.onscroll = GetScrollPosition;

    function GetScrollPosition() {
        window.external.notify(window.pageXOffset + "," + window.pageYOffset);
    }

    function SetScrollPosition(X, Y) {
        window.scrollTo(X, Y);
        window.external.notify(window.pageXOffset + "," + window.pageYOffset);
    }