views:

171

answers:

1

I use a System.Windows.Forms.WebBrowser control in my application:

private System.Windows.Forms.WebBrowser 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?

+1  A: 

Well, the only difference between your two code sample seems to be the time difference between setting up your alert replacement function and calling it.

In the first case, the page might not yet be ready when you call alert; in the second case, there might have been enough time to set up alert before the user calls it by clicking on a button.

This is just a guess. But it might help if you wait for the page to be ready before calling alert.

stakx