使用 WPF WebBrowser 控件时如何抑制脚本错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1298255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I suppress script errors when using the WPF WebBrowser control?
提问by willem
I have a WPF application that uses the WPF WebBrowser control to display interesting web pages to our developers on a flatscreen display (like a news feed).
我有一个 WPF 应用程序,它使用 WPF WebBrowser 控件在平板显示器(如新闻提要)上向我们的开发人员显示有趣的网页。
The trouble is that I occasionally get a HTML script error that pops up a nasty IE error message asking if I would like to "stop running scripts on this page". Is there a way to suppress this error checking?
问题是我偶尔会收到一个 HTML 脚本错误,它会弹出一个令人讨厌的 IE 错误消息,询问我是否想“停止在此页面上运行脚本”。有没有办法抑制这种错误检查?
NOTE: I have disabled script debugging in IE settings already.
注意:我已经在 IE 设置中禁用了脚本调试。
采纳答案by Kyle Rozendo
The problem here is that the WPF WebBrowser
did not implement this property as in the 2.0 control.
这里的问题是 WPFWebBrowser
没有像在 2.0 控件中那样实现这个属性。
Your best bet is to use a WindowsFormsHost
in your WPF application and use the 2.0's WebBrowser
property: SuppressScriptErrors
. Even then, you will need the application to be full trust in order to do this.
最好的办法是WindowsFormsHost
在 WPF 应用程序中使用 a并使用 2.0 的WebBrowser
属性:SuppressScriptErrors
. 即便如此,您仍需要完全信任应用程序才能执行此操作。
Not what one would call ideal, but it's pretty much the only option currently.
不是人们所说的理想,但它几乎是目前唯一的选择。
回答by Wolf5
Here is a solution i just made with reflection. Solves the issue :) I run it at the Navigated event, as it seems the activeX object is not available until then.
这是我刚刚用反射制作的解决方案。解决了问题 :) 我在 Navigated 事件中运行它,因为在此之前,activeX 对象似乎不可用。
What it does is set the .Silent property on the underlying activeX object. Which is the same as the .ScriptErrorsSuppressed property which is the Windows forms equivalent.
它的作用是在底层的 activeX 对象上设置 .Silent 属性。这与 .ScriptErrorsSuppressed 属性相同,后者是 Windows 窗体等效项。
public void HideScriptErrors(WebBrowser wb, bool Hide) {
FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (fiComWebBrowser == null) return;
object objComWebBrowser = fiComWebBrowser.GetValue(wb);
if (objComWebBrowser == null) return;
objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });
}
A better version that can be run anytime and not after the .Navigated event:
一个可以随时运行的更好版本,而不是在 .Navigated 事件之后:
public void HideScriptErrors(WebBrowser wb, bool hide) {
var fiComWebBrowser = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
if (fiComWebBrowser == null) return;
var objComWebBrowser = fiComWebBrowser.GetValue(wb);
if (objComWebBrowser == null) {
wb.Loaded += (o, s) => HideScriptErrors(wb, hide); //In case we are to early
return;
}
objComWebBrowser.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { hide });
}
If any issues with the second sample, try swapping wb.Loaded with wb.Navigated.
如果第二个示例有任何问题,请尝试将 wb.Loaded 与 wb.Navigated 交换。
回答by Carol
Just found from another question, this is elegant and works great.
刚刚从另一个问题中发现,这很优雅,效果很好。
dynamic activeX = this.webBrowser1.GetType().InvokeMember("ActiveXInstance",
BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
null, this.webBrowser1, new object[] { });
activeX.Silent = true;
回答by Ashot Muradian
I've also found an interesting way to disable JavaScript errors. But you need to use at least .Net Framework 4.0 because of using elegant dynamic type.
我还发现了一种有趣的方法来禁用 JavaScript 错误。但是由于使用了优雅的动态类型,您至少需要使用 .Net Framework 4.0。
You need to subscribe to the LoadCompleted event of the WebBrowser element:
您需要订阅 WebBrowser 元素的 LoadCompleted 事件:
<WebBrowser x:Name="Browser"
LoadCompleted="Browser_OnLoadCompleted" />
After that you need to write an event handler that looks like below:
之后,您需要编写一个如下所示的事件处理程序:
void Browser_OnLoadCompleted(object sender, NavigationEventArgs e)
{
var browser = sender as WebBrowser;
if (browser == null || browser.Document == null)
return;
dynamic document = browser.Document;
if (document.readyState != "complete")
return;
dynamic script = document.createElement("script");
script.type = @"text/javascript";
script.text = @"window.onerror = function(msg,url,line){return true;}";
document.head.appendChild(script);
}
回答by alexb
I wanted to add this as a comment to @Alkampfer answer, but I don't have enough reputation. This works for me (Windows 8.1, NET 4.5):
我想将此添加为@Alkampfer 答案的评论,但我没有足够的声誉。这对我有用(Windows 8.1、NET 4.5):
window.Browser.LoadCompleted.Add(fun _ ->
window.Browser.Source <- new System.Uri("javascript:window.onerror=function(msg,url,line){return true;};void(0);"))
This code sample is written in F#, but it's pretty clear what it does.
此代码示例是用 F# 编写的,但它的作用非常清楚。
回答by Darey
Check the below code for suppressing script errors for WPF browser control..
检查以下代码以抑制 WPF 浏览器控件的脚本错误..
public MainWindow
{
InitializeComponent();
WebBrowserControlView.Navigate(new Uri("https://www.hotmail.com"));
//The below checks for script errors.
ViewerWebBrowserControlView.Navigated += ViewerWebBrowserControlView_Navigated;
}
void ViewerWebBrowserControlView_Navigated(object sender, NavigationEventArgs e)
{
BrowserHandler.SetSilent(ViewerWebBrowserControlView, true); // make it silent
}
public static class BrowserHandler
{
private const string IWebBrowserAppGUID = "0002DF05-0000-0000-C000-000000000046";
private const string IWebBrowser2GUID = "D30C1661-CDAF-11d0-8A3E-00C04FC9E26E";
public static void SetSilent(System.Windows.Controls.WebBrowser browser, bool silent)
{
if (browser == null)
MessageBox.Show("No Internet Connection");
// get an IWebBrowser2 from the document
IOleServiceProvider sp = browser.Document as IOleServiceProvider;
if (sp != null)
{
Guid IID_IWebBrowserApp = new Guid(IWebBrowserAppGUID);
Guid IID_IWebBrowser2 = new Guid(IWebBrowser2GUID);
object webBrowser;
sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser);
if (webBrowser != null)
{
webBrowser.GetType().InvokeMember("Silent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { silent });
}
}
}
}
[ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleServiceProvider
{
[PreserveSig]
int QueryService([In] ref Guid guidService, [In] ref Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject);
}
Whereas, If you are using Winforms Web browser with winforms host.. you have a property "SuppressScriptErrors" set it to true
然而,如果您使用带有 winforms 主机的 Winforms Web 浏览器.. 您有一个属性“SuppressScriptErrors”将其设置为 true
<WindowsFormsHost Name="WinformsHost" Grid.Row="1">
<winForms:WebBrowser x:Name="WebBrowserControlView" ScriptErrorsSuppressed="True" AllowWebBrowserDrop="False"></winForms:WebBrowser>
</WindowsFormsHost>
回答by Alkampfer
I've this problem in the past and finally resolved it with an injection of a Javascript script that suppress error handling. Hope this could help you too.
我过去遇到过这个问题,最后通过注入抑制错误处理的 Javascript 脚本解决了这个问题。希望这也能帮到你。
回答by Mwaffak Jamal Zakariya
you can use this trick
你可以使用这个技巧
vb.net
网络
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Integer, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
Private Const WM_CLOSE As Short = &H10s
and call last lib :
并调用最后一个 lib :
dim hwnd
dim vreturnvalue
hwnd = FindWindow(vbNullString,"script error")
if hwnd<>0 then vreturnvalue = SendMessage(hwnd, WM_CLOSE, &O0s, &O0s)