Luckily DOM's window has so called "external" object and WebBrowser componenet has a "ObjectForScripting" property which is "equal" to "window.external".
There are some restrictions with permissions, f.e. you cannot set your window or application as a ObjectForScripting. Otherwise you receive Exception "The object type is not visible to COM. You need to set ComVisibleAttribute attribute to True."
So I propose to use another class to do that.
Here is the source:
1st Part of code is run only once, in the window/app constructor f.e.
ObjectForScriptingHelper ScriptHelper = new ObjectForScriptingHelper(this);
wb_browser.ObjectForScripting = ScriptHelper;
2nd Part is run on Browser's "Navigated" event
private void wb_browser_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) {
string DisableScriptError = @"function externalError(errorMsg, document, lineNumber) {
window.external.onError(errorMsg, document, lineNumber);
return true;
}
window.onerror = externalError;";
HTMLDocument doc2 = wb_browser.Document as HTMLDocument;
IHTMLScriptElement scriptErrorSuppressed = (IHTMLScriptElement)doc2.createElement("SCRIPT");
scriptErrorSuppressed.type = "text/javascript";
scriptErrorSuppressed.text = DisableScriptError;
IHTMLElementCollection nodes = doc2.getElementsByTagName("head");
foreach (IHTMLElement elem in nodes)
{
HTMLHeadElement head = (HTMLHeadElement)elem;
head.appendChild((IHTMLDOMNode)scriptErrorSuppressed);
}
}
3rd Part of script is that special class:
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[ComVisible(true)]
public class ObjectForScriptingHelper
{
TestingWindow m_Window;
public ObjectForScriptingHelper(TestingWindow w)
{
m_Window = w;
}
public void onError(Object arg1, Object arg2, Object arg3)
{
m_Window.onError(arg1, arg2, arg3);
}
}
And 4th Part of code is point where you can write your code:
public void onError(Object arg1, Object arg2, Object arg3) {
//Put your handle here
}
GL & HF
SE keywords:
How to capture script error message in a WPF WebBrowser
No comments:
Post a Comment