NoWar
NoWar

Reputation: 37633

How to inject <DIV> into WPF WebBrowser Control to overlap all webpage content within?

What I want to do is when WPF WebBrowser loads page I just want to put over page content some to prevent any click events from user within downloaded page.

So the idea is somehow insert that including it style into downloaded page...

Is it possible to do?

If yes, then how it could be implemented in C#?

Upvotes: 1

Views: 1836

Answers (1)

Zenexer
Zenexer

Reputation: 19613

Can you navigate to a javascript: URL? That's probably the cheap way to do it, and I believe that's what I ended up doing in the past.

There's another way involving directly accessing the DOM. It involves accessing WebBrowser.Document, which you can cast to a COM type. I'll need to get back to you on the exact technique--I have it saved somewhere--but there's a tiny bit of a hint on MSDN.

Edit:

The easiest way to test the JavaScript would be to do something like:

webBrowser.Navigate("javascript:alert('Test');")

If you get a dialog saying Test without your web page disappearing, it works. You can insert any JavaScript you want there, provided the test worked. For example:

webBrowser.Navigate("javascript:void(document.body.innerHTML = '<div>Test</div>' + document.body.innerHTML);");

The Proper Way

I'm going to give this a shot, but it's untested, so keep in mind that you might need to tweak this process a bit.

  1. Reference to ShDocVw.dll.
  2. Add a using statement for the mshtml namespace.
  3. Cast the WebBrowser.Document object to an mshtml.IHTMLDocument2 interface.
  4. This should give you access to the document's DOM, so you should be able to use IntelliSense to figure out what to do from here. You'll be using COM, though, so it will be a bit of a pain, and will require a lot of work with interfaces.

Edit: This question has some good examples. I would use plain casting instead of the as keyword, though. obj as Something is syntax sugar for obj is Something ? (Something)obj : null. That extra test really is unnecessary here.

Upvotes: 3

Related Questions