【问题标题】:WebView events not firing in Xamarin.FormsWebView 事件未在 Xamarin.Forms 中触发
【发布时间】:2022-08-02 17:06:26
【问题描述】:

我想从 WebView 页面获取 HTML,所以我使用 EvaluateJavaScriptAsync 函数来获取正文。但是,这会引发 NRE,可能是因为我在页面加载之前获取文档。因此,我将 lambda 表达式添加到 Navigated 事件。

var wv = new WebView();
wv.Source = \"https://www.bbc.com/news\";
wv.Navigated += async (s, e) =>
{
    var x = await wv.EvaluateJavaScriptAsync(\"document.body.innerHTML\");
    Debugger.Break();
};

但是,执行永远不会breaks,即Navigated 事件不会被触发。我尝试过其他事件,并意识到Navigating 事件也永远不会触发。这也不适用于任何其他网站。知道发生了什么吗?

或者,有没有其他方法可以在 Xamarin 中进行动态网页抓取,而且不会太贵?谢谢。

    标签: c# xamarin.forms


    【解决方案1】:

    这是一个关于使用CoreWebView2.ExecuteScriptAsync() 从 webview 页面获取 html 的演示。

    public Form1()
                {
                    InitializeComponent();
                }
         
                private void button1_Click(object sender, EventArgs e)
                {
                    this.webView2.Source = new System.Uri(textBox1.Text, System.UriKind.Absolute);
                }
                private async void webView2_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
                {
         
                    object obj = await webView2.CoreWebView2.ExecuteScriptAsync("document.body.innerHTML");
                    textBox2.Text = obj.ToString();
                }
         
                private async void button2_Click(object sender, EventArgs e)
                {
                    object obj = await webView2.CoreWebView2.ExecuteScriptAsync("document.body.innerHTML");
                    textBox2.Text = obj.ToString();
                }
         
         
         
                private async void button3_Click(object sender, EventArgs e)
                {
                    object obj = await webView2.CoreWebView2.ExecuteScriptAsync("document.body.innerText");
                    textBox2.Text = obj.ToString();
                }
         
                private async void button4_Click(object sender, EventArgs e)
                {
                    object obj = await webView2.CoreWebView2.ExecuteScriptAsync("$('.f3')[0].innerHTML");
                    textBox2.Text = obj.ToString();
                }
        
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多