C# Insert dynamic html - html injection

While creating a plugin for IE, I've encountered several problems like how to create a popup form when a certain condition has been met. And how to add dynamic css and javascript to the document page.

What I did.

In IE's DocumentComplete method you will get the url and web browser object. (Actually I've tried 2 IE framework in doing an IE plugin, spicie and add-in express). But eventually I've use add-in because spicie hasn't been updated for a long time.

How to get the doc element:
var webBrowser = pDisp as IWebBrowser2;
var doc2 = webBrowser.Document as IHTMLDocument2;
Add-in, readily available through HTMLDocument getter.

Add dynamic html:
var element = doc2.createElement("div");
element.innerHTML = "Hello czetsuya";
element.setAttribute("id", "myDiv", 0);
element.setAttribute("class", "myDivClass", 0);
doc2.body.insertAdjacentHTML("afterBegin", element.outerHTML);

Adding js and css:
var headElem = (IHTMLElement)(doc2.getElementsByTagName("head").item(null, 0));
if (headElem != null)
  var styleSheet = doc2.createStyleSheet("", 0);
  styleSheet.cssText = @".myDivClass { cursor: move }";

var js = "function sayHi(alert(\"Hello czetsuya\"))";
var scriptElem = (IHTMLScriptElement)doc2.createElement("script");
scriptElem.type = @"text/javascript";
scriptElem.text = @"" + js + "";
window.execScript("sayHi()", null); 
C# Insert dynamic html - html injection C# Insert dynamic html - html injection Reviewed by Edward Legaspi on Tuesday, May 03, 2011 Rating: 5

No comments:

Powered by Blogger.