1

How to detect which HTML element (tag) was clicked in TWebBrowser when DesignMode is ON?

The problem:
When DesignMode is on:

  • Document_OnMouseOver never executes.
  • The document never completes loading.
  • BeforeNavigate2 is not called when I click a link.

Update:
The thing that I need is IHTMLTxtRange (I think). It works when I double click a link/word. But I don't know how to get the tag under caret when no text/link is selected.

procedure TForm1.getRange;
var
  Sel: IHTMLSelectionObject;
  Range: IHTMLTxtRange;
  Doc: IHTMLDocument2;
begin
    Doc := EmbeddedWB.Doc2;
    if Assigned(Doc) then
    begin
      Sel := Doc.selection;
      if Assigned(Sel) then
      begin
        if (Sel.type_ = 'None') or (Sel.type_ = 'Text') then
        begin
          Range := Sel.createRange as IHTMLTxtRange;
          Range.expand('word');

          Memo.Text:=
              Range.htmlText + crlf +    // full tag
              Range.text;                // only text
        end;
      end;
end;
Gabriel
  • 20,797
  • 27
  • 159
  • 293
  • I don't think that the active element is what you want. Surely you need to get the coordinates (client coordinates), and call `IHtmlDocument2.elementFromPoint`. – David Heffernan Feb 08 '17 at 10:04
  • you can get the link in OnBeforeNavigate event – whosrdaddy Feb 08 '17 at 10:19
  • Hi David. I already tried that yesterday but with no luck. I only get 'BODY'. Here is the code: http://stackoverflow.com/questions/42110608/twebbrowser-detecting-the-tag-under-cursor-on-click – Gabriel Feb 08 '17 at 10:30
  • Just consume the event? Look [here](http://stackoverflow.com/a/8579489/800214) for a nice example and [here](https://msdn.microsoft.com/en-us/library/aa768326(v=vs.85).aspx) for the official documentation. – whosrdaddy Feb 08 '17 at 12:25
  • @DarkPresidentOfAmerica: does this help you or not? – whosrdaddy Feb 08 '17 at 16:02
  • @whosrdaddy-Nope. That won't help because I have DesignMode = ON so the BeforeNavigate2 won't be called when I click a (any) link. Any other ideas? – Gabriel Mar 07 '17 at 11:06
  • @whosrdaddy-The thing that I need is IHTMLTxtRange (I think). It works when I double click a link/word. But I don't know how to get the tag under caret when no text/link is selected. – Gabriel Mar 07 '17 at 12:23

1 Answers1

1

This is example how to use mouse coordenates to get the element that was clicked in webbrowser!

 var
  X, Y: Integer;
  document,E: OleVariant;
begin
  if (Msg.message = WM_LBUTTONDOWN) and IsDialogMessage(WebBrowser1.Handle, Msg) then
  begin
    X := LOWORD(Msg.lParam);
    Y := HIWORD(Msg.lParam);
    document := WebBrowser1.Document;
    E := document.elementFromPoint(X, Y);
   Edit1.Text := 'You clicked on:' + E.outerHTML;
  end;
  Handled := False;
end;
Zink
  • 13
  • 3