2

Is it possible to detect the DOM elements under a spot the user taps on a website using the WP7 WebBrowser control? I would like to let the user identify certain sections of the rendered page.

Brent Schooley
  • 782
  • 1
  • 6
  • 20

2 Answers2

4

Yes. This code works pretty well for me:

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        // first define a new function which serves as click handler
        webBrowser1.InvokeScript("eval", "this.newfunc_eventHandler = function(e) { window.external.notify(e.srcElement.tagName); }");
        // attach function to body
        webBrowser1.InvokeScript("eval", "document.body.addEventListener('click', newfunc_eventHandler, false);");
    }

    private void webBrowser1_ScriptNotify(object sender, NotifyEventArgs e)
    {
        // this should be called every time you tap an element; the value should be its tag name
        Debug.WriteLine(e.Value);
    }

It goes along Justin's answer (who beat me while coding). It first defines a click handler which then is attached to the page's body (all via InvokeScript). Every time you tap an element ScriptNotify should be called on the WebBrowser reporting the tapped element's tag name.

Make sure you have set IsScriptEnabled true for your browser control.

Heinrich Ulbricht
  • 10,064
  • 4
  • 54
  • 85
1

I'm guessing you'd have to build something off of the ScriptNotify Event.

At that point, you would register a JavaScript Event handler as usual but that event handler would, in turn, call window.external.notify("someMessageToHandle");. You would then have to route the calls appropriately.

If you don't have the ability to add the JavaScript event handlers directly on the page, you could instead add them using WebBrowserControl.InvokeScript.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536