在WebBrowser控件中无法使用Console.Log()

4

我正在使用C# Windows Forms编写JavaScript编码UI界面。以下是当"Run"按钮被按下时的代码,希望对您有帮助:

//If the button in the upper-right corner is clicked
    private void run_Click(object sender, EventArgs e)
    {
        //If the program isn't running
        if (!running)
        {
            //Show the web browser
            webBrowser1.Visible = true;
            richTextBox1.Visible = false;
            //Set the label to Running
            status.Text = "Running";
            //Set the html text to this below
            webBrowser1.DocumentText = "<!DOCTYPE html><html><body><script>\n" + richTextBox1.Text + "\n</script></body></html>";
            //Set the "run" button to "stop"
            run.Text = "Stop";
            //Set the status to running
            running = true;
        }
        //otherwise
        else
        {
            //Show the text box
            webBrowser1.Visible = false;
            richTextBox1.Visible = true;
            //Set the label to Ready
            status.Text = "Ready";
            //Go to nothingness
            webBrowser1.Navigate("about:blank");
            //Set the "stop" button to "run"
            run.Text = "Run";
            //Set the status to not running
            running = false;
        }
    }

我运行程序,大部分情况下都能正常工作。但是当我尝试使用console.log()命令时,出现以下错误:

'console' is undefined

我也尝试了 Console.Log (我其实不会 JavaScript,只是尽力而为),但是返回相同的错误,即“Console”未定义。
另外,一旦我成功让 console.log 运行,如何在 WebBrowser 控件上打开控制台?我尝试在互联网上搜索,但这两个问题都没有得到解答。
2个回答

10

您可以从Visual Studio中获取JavaScript控制台输出。

默认情况下,webBrowser1控件使用IE7来呈现其输出。 IE7没有console.log()函数。 为了使console.log()函数正常工作,您需要添加以下meta标记:

<meta http-equiv="X-UA-Compatible" content="IE=11">

如果您使用'IE=8'或更高版本,则应将console.log()功能用于调试。

当您调试Windows Forms应用程序时,它会使用.NET托管代码调试器进行调试。 为了进行不同的调试,请尝试选择“调试”>“启动而不调试”,而不是按“播放”进行调试。现在,一旦您的应用程序正在运行,请转到“调试”>“附加到进程”并找到您的WindowsFormsApplication.exe,使用Script Code Debugger(而不是.NET Managed Code debugger)附加到它。

现在,在Visual Studio中:

  • 您可以打开“调试”>“窗口”>“JavaScript控制台”
  • 您也可以打开“调试”>“窗口”>“DOM资源管理器”

你怎么可能“发现”这些步骤...(脑袋都炸了)...不管怎样,它还是起作用了 - 谢谢! - bendecko

9
是的,控制台类在您的浏览器控件中不可用,但是您可以创建一个类似于以下的记录器类。
[ComVisible(true)]
public class Logger
{
    public void log(string s)
    {
        Console.WriteLine(s);
    }
}

并在您的浏览器控件中使用它

webBrowser1.ObjectForScripting = new Logger();
webBrowser1.DocumentText = "<script>external.log('TEST');</script>";

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