Embedding/NewApi/XpcomAccess

From MozillaWiki
Jump to: navigation, search

Access to underlying XPCOM API

MozView provides a GetInterfaceRequestor() method for accessing the underlying API. This returns an InterfaceRequestor which you can use to get access to the XPCOM object you need.

NOTE: currently it is the InterfaceRequestor from nsIWebBrowser which is returned and thus the interfaces from that which is accessible.

DOM access sample

Here is a small example of using this for DOM access. You could e.g. call this code as response to the DocumentLoaded method of MozViewListener.

Include Files

You will need to have your build paths set correctly to pick up these include files.

#include "xpcom-config.h"
#include "mozilla-config.h"
#include "nsXPCOMGlue.h"
#include "nsCOMPtr.h"
#include "nsEmbedString.h"
#include "nsIInterfaceRequestor.h"
#include "nsIInterfaceRequestorUtils.h"

#include "nsIDOMHTMLDocument.h"
#include "nsIDOMDocument.h"
#include "nsIDOMHTMLElement.h"
#include "nsIDOMText.h"

Get a nsIDOMDocument from the MozView

  // pointer to your MozView
  MozView* pMozView;
  ...
  nsCOMPtr<nsIInterfaceRequestor> requestor;
  pMozView->GetInterfaceRequestor(getter_AddRefs(requestor));
  nsCOMPtr<nsIDOMDocument> doc = do_GetInterface(requestor);

Use QI to get the nsIDOMHTMLDocument

Note, that we can't do this directly from the InterfaceRequestor as it will only give us the nsIDOMDocument.

  nsCOMPtr<nsIDOMHTMLDocument> htmldoc = do_QueryInterface(doc);

Manipulate the DOM

If we get a valid nsIDOMHTMLDocument, use it to append a div to the body containing a hr and some text.

  if (htmldoc)
  {
    nsCOMPtr<nsIDOMNode> retval;
    nsCOMPtr<nsIDOMHTMLElement> body;
    htmldoc->GetBody(getter_AddRefs(body));
    nsCOMPtr<nsIDOMElement> newdiv;
    doc->CreateElement(NS_LITERAL_STRING("div"), getter_AddRefs(newdiv));
    nsCOMPtr<nsIDOMElement> newhr;
    doc->CreateElement(NS_LITERAL_STRING("hr"), getter_AddRefs(newhr));
    newdiv->AppendChild(newhr, getter_AddRefs(retval));
    nsCOMPtr<nsIDOMText> text;
    doc->CreateTextNode(NS_LITERAL_STRING("Provided by MozEmbed"), getter_AddRefs(text));
    newdiv->AppendChild(text, getter_AddRefs(retval));
    body->AppendChild(newdiv, getter_AddRefs(retval));
  }