简体   繁体   English

是否有可能在 WebBrowser 控件中调试 JavaScript 代码

[英]Is there a possibility to debug JavaScript code in a WebBrowser control

I'm writing a web page using HTML and Javascript.我正在使用 HTML 和 Javascript 编写网页。 This page is opened in WPF WebBrowser control.此页面在 WPF WebBrowser 控件中打开。 The problem is that JavaScript on this page works fine in Internet Explorer directly but not in WebBrowser control even I've set to use Internet Explorer 11 for WebBrowser control.问题是此页面上的 JavaScript 可以直接在 Internet Explorer 中正常工作,但在 WebBrowser 控件中却无法正常工作,即使我已设置为将 Internet Explorer 11 用于 WebBrowser 控件。

So I can't reproduce the issue in a usual browser to debug it.所以我无法在通常的浏览器中重现这个问题来调试它。 It's reproducible only in WebBrowser control.它只能在 WebBrowser 控件中重现。

Is there a possibility to debug JavaScript code in WebBrowser to be able to find the issue?是否有可能在 WebBrowser 中调试 JavaScript 代码以找到问题? I don't see any item with "Inspect" word in the context menu of WebBrowser.我在 WebBrowser 的上下文菜单中没有看到任何带有“Inspect”字样的项目。

Your problems are probably due to the WebBrowser control using an older version of IE than you are running standalone in Windows.您的问题可能是由于WebBrowser控件使用的 IE 版本比您在 Windows 中独立运行的版本旧。

Yes you can debug your web page.是的,您可以调试您的网页。 JavaScript has an event called window.onerror that acts like a global try/catch. JavaScript 有一个名为window.onerror的事件,它的作用类似于全局 try/catch。 This is great for catching unexpected exceptions.这对于捕获意外异常非常有用。

Add this to your JavaScript to add your own event handler:将此添加到您的 JavaScript 以添加您自己的事件处理程序:

window.onerror = function(message, url, lineNumber) 
{ 
  window.external.errorHandler(message, url, lineNumber);
}

The event handler is going to call a method in your WPF application to show you the error details.事件处理程序将调用 WPF 应用程序中的方法以显示错误详细信息。

Create a class in your WPF application like this that your JavaScript will be able to access.在您的 WPF 应用程序中创建一个这样的类,您的 JavaScript 将能够访问它。

[System.Runtime.InteropServices.ComVisibleAttribute(true)] 
public class ScriptInterface 
{ 
    void errorHandler(string message, string url, string lineNumber) 
    { 
        MessageBox.Show(string.Format("Message: {0}, URL: {1}, Line: {2}"));
    } 
}

Then set the WebBrowser control's ObjectForScripting property to an instance of your handler class:然后将 WebBrowser 控件的ObjectForScripting属性设置为处理程序类的实例:

webBrowser1.ObjectForScripting = new ScriptInterface();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM