0

In my application I need to use a WebBrowser control to process user login. I use WPF and it's WebBrowser control. The problem is that I want to display a part of web page that is under certain div. I found a solution to this, I need to inject an javascript script into a loaded html page, but I have no clue how to do it :(

This is the script that I would like to inject into web.

function showHide() { 
     $('body >').hide(); 
     $('#div').show().prependTo('body'); 
}

So i could later call it webbrowser1.InvokeScript("showHide");

I read a lot of posts on stack, but all of them refer to WindowsForms WebBrowser and it is not working with WPF one.

EDIT: I tried:

private void PageLoaded (object sender, NavigationEventArgs e)
{
    var webBrowser = sender as WebBrowser;

    webBrowser.Document.InvokeScript("execScript",
            new object[] {"$('body >').hide(); $('#" + _div + "').show().prependTo('body');"});

} 

But webBrowser.Document is type object and I cannot call InvokeScript on it, have no clue to what I should cast it.

Thanks for help.

vip1all
  • 122
  • 11
  • 1
    Possible duplicate of [How to inject Javascript in WebBrowser control](http://stackoverflow.com/questions/7998996/how-to-inject-javascript-in-webbrowser-control) – Equalsk Apr 12 '17 at 09:40
  • It is not working with WPF control so it is not duplicate... – vip1all Apr 12 '17 at 09:44
  • Did you try anything at all? It seems you've put 0 effort into your question and 0 effort into using an answer. Although it required a slight change this does work with a WPF WebBrowser just fine and is a duplicate... – Equalsk Apr 12 '17 at 09:59
  • Before asking I spent 2 days trying to solve the issue. But couldn't solve the problem. So here I am asking. – vip1all Apr 12 '17 at 10:03
  • So now do you believe me? ;-) Glad you got it working. – Equalsk Apr 12 '17 at 10:18
  • I get to the point `var script = var script = (mshtml.IHTMLScriptElement)doc.createElement("script");doc.createElement("script");` and I didn't know to what I should cast it. But before I finished editing you posted your answer. Thanks. – vip1all Apr 12 '17 at 10:27

1 Answers1

1

Add a reference to mshtml

enter image description here

In whatever event you want to inject the JavaScript:

var doc = (mshtml.HTMLDocument)webBrowser1.Document;
var head = doc.getElementsByTagName("head").Cast<mshtml.HTMLHeadElement>().First();
var script = (mshtml.IHTMLScriptElement)doc.createElement("script");
script.text = "function myFunction() { alert(\"Hello!\");}";
head.appendChild((mshtml.IHTMLDOMNode)script);

In whatever event you want to invoke the JavaScript from:

webBrowser1.InvokeScript("myFunction");

Result:

enter image description here

Equalsk
  • 7,954
  • 2
  • 41
  • 67