question about System.Windows.Forms.WebBrowser
I use a System.Windows.Forms.WebBrowser
control in my application:
private System.Windows.Forms.WebB开发者_开发技巧rowser objBrowser;
Anywhere my objBrowser
navigated, I want it to have this javascript function:
function alert(message)
{
window.external.handleMessage(message);
}
that overrides alert function.
When i use this:
private void objBrowser_DocumentCompleted(
object sender, WebBrowserDocumentCompletedEventArgs e)
{
objBrowser.Url = new Uri(
"javascript:function alert(message){window.external.handleMessage(message);};");
objBrowser.Document.InvokeScript("alert", new object[] { "hello" });//line 1
}
public void handleMessage(object obj)
{
string msg = obj.ToString();
}
alert function in java script doesn't pass the message into my form. But when i use this:
private void button1_Click(object sender, EventArgs e)
{
objBrowser.Document.InvokeScript("alert", new object[] { "hello" });
}
private void objBrowser_DocumentCompleted(
object sender, WebBrowserDocumentCompletedEventArgs e)
{
objBrowser.Url = new Uri(
"javascript:function alert(message){window.external.handleMessage(message);};");
}
public void handleMessage(object obj)
{
string msg = obj.ToString();
}
and click on button1
my form's handleMessage method executed with a object that contains "hello" string.
I want to override alert function in java script in any page that objBrowser will navigate.
How can I do this?
use below code
Private Sub webDest_Navigated(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserNavigatedEventArgs) Handles webDest.Navigated
injectAlertBlocker()
End Sub
Sub injectAlertBlocker()
Dim head As HtmlElement = webDest.Document.GetElementsByTagName("head")(0)
Dim scriptEl As HtmlElement = webDest.Document.CreateElement("script")
Dim element As IHTMLScriptElement = CType(scriptEl.DomElement, IHTMLScriptElement)
Dim alertBlocker As String = "window.alert = function () { }"
element.text = alertBlocker
head.AppendChild(scriptEl)
End Sub
精彩评论