如何让JavaScript在WebBrowser控件中运行?

3
在我的winforms应用程序中,我有一个名为webBrowser1的WebBrowser控件。
在代码中,我只是添加了浏览网页的功能:
private void Form1_Load(object sender, EventArgs e)
{
    webBrowser1.Navigate("http://localhost:6489/Default.aspx");
}

我导航到的页面的代码是:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TableRowShow.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
      window.onload = function()
      {
        document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
      }

      function attach()
      {
        document.getElementById('addDestination').setAttribute('onclick', 'addDest();');
      }

      var i = 1; // position of next tr to be shown

      function addDest()
      {
        var trs = document.getElementById('travelTable').getElementsByTagName('tr');

        if (trs[i] != null)
          trs[i++].style.display = "";
      }
    </script>
</head>
<body>
    <form id="form1" runat="server">
      <table id="travelTable">
        <tr>
          <td>
            <asp:TextBox runat="server" />
          </td>
        </tr>
        <tr style="display: none">
          <td>
            <asp:TextBox runat="server" />
          </td>
        </tr>
        <tr style="display: none">
          <td>
            <asp:TextBox runat="server" />
          </td>
        </tr>
      </table>
      <asp:HyperLink runat="server" ID="addDestination"
        ClientIDMode="Static"  NavigateUrl="javascript:;" >
        Add Destination
      </asp:HyperLink>
    </form>
</body>
</html>

在像IE或Chrome这样的浏览器中,该页面看起来是这样的:

点击“添加目标”链接将创建一个新输入:

我在WebBrowser控件中遇到的问题是它加载了页面,但JavaScript不起作用。即使在Chrome或IE中同一页面也可以正常工作,但如果我点击“添加目标”,什么也不会发生。
放置断点并使用以下代码:
webBrowser1.Document.InvokeScript("addDestination");

在立即窗口中输入并继续运行程序会激活该函数中的JavaScript,从而添加一个新的输入。

感谢回复!

2个回答

2

尝试像这样附加点击处理程序,而不是在onloadattach函数中使用setAttribute

document.getElementById('addDestination').onclick = addDest;

问题已经解决了。你有什么想法为什么在其他浏览器中使用setAttribute不起作用?我正在Windows中使用IE8,它可以正常工作。难道WebBrowser也使用IE8(最新安装的IE)吗? - Răzvan Flavius Panda

0

我尝试将其设置为false(在导航行之前添加),但没有出现错误。错误应该在哪里看到? - Răzvan Flavius Panda
据我所知,应该会弹出一个消息框。 - Uwe Keim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接