【问题标题】:WebBrowser not running javascriptWebBrowser 没有运行 javascript
【发布时间】:2016-01-17 15:50:07
【问题描述】:

我正在使用 WPF 应用程序中的 System.Windows.Forms.WebBrowser(在单独的 .dll 文件中使用)来在后台打印一些 HTML 内容。
我的问题是 HTML 元素不受页面中 javascript 的影响。
我知道页面中没有错误,因为如果我在 DocumentCompleted 事件之后复制其内容并将其粘贴到纯 HTML 文件中,脚本就可以工作。
我的 HTML 模板:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<script>
    function loaded() {
        document.getElementById("content").innerHTML = "after javascript";
    }
</script>
</head>
<body onload="loaded()">
    <h1 id="content">before javascript</h1> <!--<= This value does not change-->
</body>
</html>

我使用这个 HTML 如下:

private void PrintTest()
{
    string curDir = Directory.GetCurrentDirectory();
    string fullPath = Path.Combine(curDir, "PrintDocs\\HTMLPage1.html");

    string html = File.ReadAllText(fullPath);

    HtmlPrint.Print(html);
}

public static class HtmlPrint
{
    public static void Print(string html, string documentTitle = "")
    {
        var wb = new System.Windows.Forms.WebBrowser { DocumentText = html };
        wb.DocumentCompleted += wb_DocumentCompleted;
    }

    private static void wb_DocumentCompleted(object sender, System.Windows.Forms.WebBrowserDocumentCompletedEventArgs e)
    {
        var wb = ((System.Windows.Forms.WebBrowser)sender);

        wb.Print();
        wb.Dispose();
    }
}

我在这里错过了什么?

【问题讨论】:

标签: javascript c# html wpf printing


【解决方案1】:

你忘记了 onload 中的大括号:

<body onload="loaded()">

【讨论】:

  • nice catch 但这只是我做的一个测试(我对js不太熟悉),两种情况下的结果都是一样的
【解决方案2】:

正如我的 cmets 中所述,您可以从 C# 代码中调用 InvokeScript() 方法并传入您的 js 函数名,这应该可以解决问题。

wb.Document.InvokeScript("loaded");

【讨论】:

  • 我认为 javascript 在 DocumentCompleted 事件之后执行。如果我在页面中有 alert("HELLO!"),则 DocumentCompleted 处理程序完成后会出现弹出窗口。这给我带来了问题,因为我想访问页面上由 javascript 设置的值。我最终在 DocumentCompleted 处理程序中触发了一个计时器,该计时器等待了一秒钟;在 timer_tick 处理程序上,我可以获取现在填充的值。
【解决方案3】:

我认为你必须将onload="loaded" 更改为onload="loaded()"

【讨论】:

    猜你喜欢
    • 2022-09-27
    • 2012-07-14
    • 2012-02-28
    • 1970-01-01
    • 2011-11-12
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多