【问题标题】:How to bind to HTML from C#? [duplicate]如何从 C# 绑定到 HTML? [复制]
【发布时间】:2019-12-30 08:23:52
【问题描述】:

我想通过 C# 在 HTML 中执行一个函数,但出现错误。

由于浏览器内部有地图,所以不能省略“导航”功能。

javascript

<!DOCTYPE html>
<html>
    <head>
    <title>test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="initial-scale=1.0,user-scalable=no">
    <script>
        function CallScrript(va1, va2)
        {
            alert('Val1 : ' + val1 + ' / Val2 : ' + val2);
        }
    </script>
    </head>
    <body>
    </body>
</html>

C#代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.webBrowser1.Navigate("http://1xx.xxx.xxx.xxx/test.html");

            ExecJavascript("abc", "bcd");
        }

        private void ExecJavascript(string sValue1, string sValue2)
        {
            try
            {
                webBrowser1.Document.InvokeScript("CallScript", new object[] { sValue1, sValue2 });
            }
            catch(Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
    }
}

错误信息:

system.nullreferenceexception 对象引用未设置为对象的实例。

【问题讨论】:

    标签: javascript c# winforms webbrowser-control


    【解决方案1】:

    你得到NullReferenceException是因为当你调用你的方法时Document属性还不存在..

    您可能需要文档加载完成事件的委托来触发您要执行的任何操作..

    this.webBrowser1.NavigationCompleted += webView1_NavigationCompleted;
    
    private void webView1_NavigationCompleted(WebView sender, WebViewControlNavigationCompletedEventArgs args)
    {
        if (args.IsSuccess == true)
        {
            statusTextBlock.Text = "Navigation to " + args.Uri.ToString() + " completed successfully.";
        }
        else
        {
            statusTextBlock.Text = "Navigation to: " + args.Uri.ToString() +
                                   " failed with error " + args.WebErrorStatus.ToString();
        }
    }
    

    您可以在MSDN here 上阅读有关不同活动的更多信息。

    【讨论】:

      猜你喜欢
      • 2012-10-24
      • 1970-01-01
      • 2016-04-11
      • 2012-03-30
      • 2019-02-10
      • 1970-01-01
      • 2014-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多