如何从C#绑定HTML?调用HTML函数遇空引用异常求助
解决C# WebBrowser调用JavaScript函数的NullReferenceException问题
嘿,我来帮你搞定这个问题!你遇到的空引用异常主要有几个明确的原因,咱们一步步拆解解决:
问题重现
你的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: 对象引用未设置到对象的实例。
问题原因分析
- WebBrowser.Navigate是异步操作:你在Form构造函数里刚调用Navigate就立刻执行
ExecJavascript,这时候网页还没加载完成,webBrowser1.Document还是null,自然会抛出空引用异常。 - 函数名拼写不匹配:JS里的函数名是
CallScrript(注意有两个r),但C#里调用的是CallScript(只有一个r),就算Document加载好了,也找不到对应的函数。 - JS内部参数拼写错误:JS函数的参数是
va1,但alert里写的是val1(多了一个l),就算调用成功也会弹出undefined。
修复方案
步骤1:等待网页加载完成再调用JS函数
把调用ExecJavascript的逻辑移到WebBrowser的DocumentCompleted事件里,这个事件会在网页完全加载完成后触发。
步骤2:修正所有拼写错误
- 统一JS和C#里的函数名(比如都改成
CallScript) - 修正JS里的参数引用错误
修改后的完整代码
修正后的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 CallScript(val1, val2) { alert('Val1 : ' + val1 + ' / Val2 : ' + val2); } </script> </head> <body> </body> </html>
修正后的C#代码:
using System; using System.Windows.Forms; namespace WindowsFormsApp4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); // 绑定DocumentCompleted事件 webBrowser1.DocumentCompleted += WebBrowser1_DocumentCompleted; this.webBrowser1.Navigate("http://1xx.xxx.xxx.xxx/test.html"); } private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { // 网页加载完成后再调用JS函数 ExecJavascript("abc", "bcd"); } private void ExecJavascript(string sValue1, string sValue2) { try { // 增加null判断,避免异常 if (webBrowser1.Document != null) { webBrowser1.Document.InvokeScript("CallScript", new object[] { sValue1, sValue2 }); } } catch(Exception e) { MessageBox.Show(e.ToString()); } } } }
这样修改后,就能正常调用JS函数啦!
内容的提问来源于stack exchange,提问作者Sh H
相关产品推荐
相关产品推荐

