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.

3
  • 1
    Possible duplicate of How to inject Javascript in WebBrowser control Commented Apr 12, 2017 at 9:40
  • It is not working with WPF control so it is not duplicate... Commented Apr 12, 2017 at 9:44
  • 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. Commented Apr 12, 2017 at 10:27

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.