简体   繁体   中英

C# Web browser control is not updating correctly

I'm currently working on an app that technically interacts with an html page that uses dynamic content.

My problem is when I try to append data to the WBC the content isn't updating correctly.

namespace CheckList
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        .... code removed ....

        private void button2_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != null)
            {
                HtmlDocument doc = webBrowser1.Document;
                HtmlElement row = doc.CreateElement("tr");
                HtmlElement cell1 = doc.CreateElement("td");
                HtmlElement cell2 = doc.CreateElement("td");
                cell1.InnerHtml = "[X] " + textBox1.Text;
                cell2.SetAttribute("class", "solved_2");
                cell2.InnerHtml = "Unsolved";
                row.AppendChild(cell1);
                row.AppendChild(cell2);
                doc.GetElementsByTagName("table")[0].AppendChild(row);
                //doc.Write(doc.GetElementsByTagName("HTML")[0].OuterHtml);
                webBrowser1.Document.Body.InnerHtml = doc.Body.InnerHtml;
            }
        }
    }
}

What currently happens is, I click "add" it should add the html to the page and update and the javascript and what not should still load.

What happens is it adds the content, but the javascript doesn't work after I attempt to reload the content. The CSS stays in tact though, and the javascript isn't working after that point.

JS Source:

var showalert = true;
var file = "file:///C:/Users/Removed/Documents/Visual Studio 2010/Projects/CheckList/CheckList/bin/Release/";
initiate_instance();

function initiate_instance() {
 //insert
 $.get(file + "saved.html", function(data) {
  //$("table#items").append("<tr><th width='70%'>Issue</th><th width='30%' class='right'>Solved</th></tr>");
  $("table#items").html($("table#items").html() + data);
 });

 //change [X] into a link
 $("table#items tr td").each(function() {
  $(this).html($(this).html().replace("[X]", "<a onclick='return remove(this)' href='#'>[X]</a>"));
 });

 //change the css
 $("table#items tr:odd").attr("class", "odd");
 $("table#items tr td:eq(0)").attr("width", "70%");
 $("table#items tr td:eq(1)").attr("width", "30%");
 $("td.solved, td.solved_2").click(function() {
  if($(this).attr("class") == "solved") {
   $(this).attr("class", "solved_2");
   $(this).text("Unsolved");
  } else {
   $(this).attr("class", "solved");
   $(this).text("Solved");
  }

  if(showalert == true) {
   alert("Remember, for these changes to keep effect please save before closing the program.");
   showalert = false;
  }
 });
}

//delete rows
function remove(obj) {
 if(showalert == true) {
  alert("Remember, for these changes to keep effect please save before closing the program.");
  showalert = false;
 }
 $(obj).parent().parent().remove();
 return false;
}

TL;DR: Have you tried setting "AllowNavigation" to true?

If you need to prevent navigation, but still need to update the page, a method I've found that works requires:

  • Initializing the WebBrowser control's DocumentText property with empty HTML to initialize the internal objects (ie: Document , DomDocument , Document.Body , etc)
  • Allowing navigation and the revoking upon page completion (if needed)

Code:

namespace CheckList
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            // Initialize all the document objects
            webBrowser1.DocumentText = @"<html></html>";
            // Add the Document Completed event handler to turn off navigation
            webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            // Load default information via LoadHtml(string html);
            LoadHtml(@"<html><head></head><body>Text!<script type='text/javascript' language='javascript'>alert('Aha!');</script></body></html>");
        }

        private void LoadHtml(string html)
        {
            webBrowser1.AllowNavigation = true;

            // This will trigger a Document Completed event
            webBrowser1.DocumentText = html;
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            // Prevent further navigation
            webBrowser1.AllowNavigation = false;

            // Clean-up the handler if no longer needed
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // Do your document building
            LoadHtml(doc.Body.Parent.OuterHtml);
        }
    }
}

I've found doing it this way:

  • Prevents users from navigating until allowed
  • Allows execution of JavaScript (immediately before OnDocumentCompleted fires)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM