Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke custom Javascript in System.Windows.Forms.WebBrowser?

I'm loading third party webpage that contains following code

<script type="text/javascript">
onDomReady(function() { some_code1; });
</script>

into WebBrowser component. After some_code1 had executed I need to do some manipulations with Dom that will make some_code1 invalid. The question is how to determine that some_code1 had executed?

I cant't do

private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    DoRequiredManipulations();
}

Since this event will occur before some_code1 has executed and will make it invalid.

Also I can't do

private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    web.Document.InvokeScript("doSome_code1");
    DoRequiredManipulations();
}

Since some_code1 is declared as an anonymous function.

It seems that the only way to do it is this:

private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    var script = GetScriptText(web.DocumentText);
    //execute script in webbrowser
    DoRequiredManipulations();
}

The problem is that I don't know how to execute this script in webbrowser. I had tried web.Navigate("javascript: " + script); but it doesn't work correctly.

like image 891
Poma Avatar asked Sep 14 '26 17:09

Poma


1 Answers

I found how to do that:

HtmlElement scriptEl = web.Document.CreateElement("script");
(scriptEl.DomElement as IHTMLScriptElement).text = "function myscript() { " + script.Text + " }";
web.Document.GetElementsByTagName("head")[0].AppendChild(scriptEl);
web.Document.InvokeScript("myscript");
like image 141
Poma Avatar answered Sep 16 '26 06:09

Poma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!