2

I have this code that will do the opposite: gets the child document given an iframe element:

var htmlWindow = (element as IHTMLFrameBase2).contentWindow;
if (htmlWindow == null) return null;
// Convert IHTMLWindow2 to IWebBrowser2 using IServiceProvider.
IServiceProvider sp = (IServiceProvider)htmlWindow;
// Use IServiceProvider.QueryService to get IWebBrowser2 object.
Object brws = null;
//brws = 
sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out brws);
// Get the document from IWebBrowser2.
SHDocVw.IWebBrowser2 browser = (SHDocVw.IWebBrowser2)(brws);
return (IHTMLDocument2)browser.Document;

My question is how can I do the opposite? I tried doing this given the child document but I'm getting a null frameWindow:

Object frameWindow;
IServiceProvider isp = (IServiceProvider)document.parentWindow;
isp.QueryService(ref IID_IWebBrowserApp, ref IID_IHTMLFrameBase, out frameWindow);

Here are all the GUIDs for your reference:

private static Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
private static Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E");
private static Guid IID_IHTMLFrameBase2 = new Guid("3050F6DB-98B5-11CF-BB82-00AA00BDCE0B");
private static Guid IID_IHTMLFrameBase = new Guid("3050F311-98B5-11CF-BB82-00AA00BDCE0B");
private static Guid IID_IHTMLWindow2 = new Guid("332C4427-26CB-11D0-B483-00C04FD90119");

And here is my IServiceProvider:

[ComImport(), ComVisible(true), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
private interface IServiceProvider
{
    [return: MarshalAs(UnmanagedType.I4)]
    [PreserveSig]
    int QueryService(ref Guid guidService, ref Guid riid, [MarshalAs(UnmanagedType.Interface)] out object ppvObject);
}
Juan
  • 15,274
  • 23
  • 105
  • 187

1 Answers1

0

Well actually you wont be able to get Iframe document/elements from the main browser. You must have to execute javascript. In my case, I had luckly jquery available in my target website so I used following express to get some text from one of the inner iframe.

I did this:

   var tmp = browser.Document.InvokeScript("eval", new object[] { "$(\"#iframe_id\").contents().find('#element').html())" });

In your case, if you really want to do something with the html of some element inside your target iframe then you should acutally grab its html and then create an empty element in the main browser window and update its html with the one you grabbed and do your stuff.

Thats the only way I found so far.

KMX
  • 2,631
  • 1
  • 23
  • 28