4

I think this should be quite simple, but I cannot make it work.

I want to detect mouse clicks on a WebView...

I've subclassed WebView, here is the code

#import <AppKit/AppKit.h>
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>

@interface ResultsWebView : WebView {
}
@end

and

#import "ResultsWebView.h"

@implementation ResultsWebView

- (void)mouseDown:(NSEvent *)theEvent {
    NSLog(@"%@", theEvent);
}

@end

In my xib file, I added a WebView and then changed the class to ResultsWebView.

I've checked in runtime and the object is a ResultsWebView, but the mouseDown event is never called...

What am I missing?

Marcos Crispino
  • 8,018
  • 5
  • 41
  • 59

3 Answers3

5

WebUIDelegate comes into rescue.

Supposing that you have a WebView instance in your NSWindowController:

WebView *aWebView;

You can set your controller as UIDelegate, as follow:

[aWebView setUIDelegate:self];

implementing the following method within your controller, you will have a form of control over mouse click events:

- (void)webView:(WebView *)sender mouseDidMoveOverElement:
(NSDictionary *)elementInformation modifierFlags:(NSUInteger)
modifierFlags
{
if ([[NSApp currentEvent] type] == NSLeftMouseUp)
  NSLog(@"mouseDown event occurred");
}

as a bonus, playing with the elementInformation dictionary you can get additional informations about the DOM element in which click event occurred.

micfan
  • 800
  • 8
  • 12
valvoline
  • 7,737
  • 3
  • 47
  • 52
  • 1
    Nice solution ! In my case, I use :[[NSApp currentEvent] type] == NSLeftMouseUp && [[NSApp currentEvent] clickCount == 2 ] to intercept a doubleClick event – Chrstpsln Jun 11 '15 at 10:08
3

The problem is that the message isn't being sent to the WebView. Instead it is being sent to the private WebHTMLView inside your WebView, which actually processes the mouse events.

http://trac.webkit.org/browser/trunk/Source/WebKit/mac/WebView/WebHTMLView.mm#L3555

You might just want to look into using javascript in your WebView to send the onmousedown events back to your objective-c class.

Patrick
  • 505
  • 5
  • 9
  • An alternative is to override -hitTest: and use it to redirect mouse down events to a custom view as suits you. – Mike Abdullah May 15 '12 at 09:33
  • Or another similar alternative is to simply create an overlay view that notes the event and forwards it to your webView. – uchuugaka Sep 20 '15 at 15:31
-2

Maybe this helps:

[window setAcceptsMouseMovedEvents:YES];
lbrndnr
  • 3,361
  • 2
  • 24
  • 34
  • No it didn't... I added it to the applicationDidFinishLaunching: app delegate method, but it didn't change anything.But thanks anyway – Marcos Crispino Mar 17 '11 at 17:44