1

I want to execute a function in HTML through C# but I get an error.

Since there is a map inside the webbrowser, I can't leave out the "Navigate" function.

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# code

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());
            }
        }
    }
}

Error message:

system.nullreferenceexception object reference not set to an instance of an object.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Sh H
  • 53
  • 4

1 Answers1

1

You're getting NullReferenceException because the Document property isn't there yet when you call your method..

You'd probably need a delegate on the document load finished event to fire off whatever you're going to do..

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();
    }
}

You can read more about different events on MSDN here.

Adrian
  • 8,271
  • 2
  • 26
  • 43