JavaScript 与 WebBrowser 控件 C#

标签 javascript c# html

最近我遇到了 C# 中 Web 浏览器控件的问题。

导航到其中实现了 JavaScript 的网页会导致 WebBrowser 崩溃 - 它声称该网页中的 JS 代码存在语法错误。 (它提供了该行以及错误所在的字符,因此我去查看导致错误的原因)。

错误示例:

  function validate_fen(fen) {
    var errors = {
       0: 'No errors.',
       1: 'FEN string must contain six space-delimited fields.',
       2: '6th field (move number) must be a positive integer.',
       3: '5th field (half move counter) must be a non-negative integer.',
       4: '4th field (en-passant square) is invalid.',
       5: '3rd field (castling availability) is invalid.',
       6: '2nd field (side to move) is invalid.',
       7: '1st field (piece positions) does not contain 8 \'/\'-delimited rows.',
       8: '1st field (piece positions) is invalid [consecutive numbers].',
       9: '1st field (piece positions) is invalid [invalid piece].',
      10: '1st field (piece positions) is invalid [row too large].',
    };

错误所在的行是 3977 字符号 5,或更具体地说是此代码中字符 5 中的最后一行(这意味着它可能是最后一个逗号,如果我错了,请纠正我)。

错误的更具体代码:

  10: '1st field (piece positions) is invalid [row too large].',
};

鉴于其他浏览器确实可以正确加载网站,包括 IE(我知道 webBrowser 和 IE 不一样),我将如何解决这些问题?

我的想法是:

  1. 在运行时修复脚本(如果可能)
  2. 无论如何都要加载脚本。

我不确定,但我认为如果出现错误,webBrowser 控件不会加载脚本,从而导致以后出现更多错误。

我将如何成功加载特定网页? 是否可以在运行时编辑脚本(该脚本不在 HTML 的头部,它在服务器上)?如果可能的话,如何实现?

最佳答案

如何在 C# 中加载和修复脚本:
从网站复制非加载脚本并修复语法错误并将其复制到您的代码中。

Important note: put all of the script's code in a function so you can call it later

使用以下代码将脚本添加到站点:

HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = script;//script is your script which you defined
head.AppendChild(scriptEl);

调用 InvokeScript 到您创建的函数。

如果您修复了所有语法错误,那就没问题了。

关于JavaScript 与 WebBrowser 控件 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29604673/

相关文章:

css - 将元素放在绝对 div 元素之后

C# 标志解析

html - 从 Bootstrap .nav-tabs 中删除一些边框

javascript - 在 PHP 中单击时使引用切换为粗体

javascript - 从 WebEngine QT 5.13.0 中的 javascript 对话框获取下载文件名

c# - Compact Framework - 是否有可用的 MVC 框架/库?

c# - List<T>.FindIndex 多个结果?

javascript - IE9 检测不到 PC 上安装的字体

javascript - 在新选项卡中的组件之间传递数据

javascript - 主 Web 文档与 iframe 脚本