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

所以我正在使用C#Windows Forms编写Javascript编码UI。 这是我按下“运行”按钮时的代码,以防它有用:

//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 = "\n" + richTextBox1.Text + "\n"; //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控件上打开控制台? 我试过在互联网上搜索,但这些问题都没有出现过。

是的,您的浏览器控件中没有控制台类,但您可以创建这样的记录器类

 [ComVisible(true)] public class Logger { public void log(string s) { Console.WriteLine(s); } } 

并在浏览器控件中使用它

 webBrowser1.ObjectForScripting = new Logger(); webBrowser1.DocumentText = ""; 

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

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

  

‘IE = 8’或更高版本应该使console.log()可用。

当您调试Windows窗体应用程序时,它使用.NET托管代码调试器进行调试。 为了进行不同的调试,请尝试选择“Debug”>“Start without Debugging”,而不是按“Play”进行调试。 现在,一旦您的应用程序运行,请转到“调试”>“附加到进程”并找到您的WindowsFormsApplication.exe, 使用脚本代码调试器而不是.NET托管代码调试器附加到它。

现在,在Visual Studio中:

  • 您可以打开“调试”>“Windows”>“JavaScript控制台”
  • 您也可以打开“Debug”>“Windows”>“DOM Explorer”