这种方法过去对我有用:
DOMElement *el = // find element somehow
DOMDocument *doc = [el ownerDocument];
DOMAbstractView *window = [doc defaultView];
DOMUIEvent *evt = (DOMUIEvent *)[doc createEvent:@"UIEvents"];
[evt initUIEvent:@"click" canBubble:YES cancelable:YES view:window detail:1];
[el dispatchEvent:evt];
我相信这是所有标准的 DOM2 事件模块 API。我想我是通过查看这篇MozDevcreateEvent
文章中的 JavaScript 找到了这个解决方案。
还要注意-[DOMHTMLElement click]
WebKit 的DOMHTMLElement.h中标记为的方法AVAILABLE_AFTER_WEBKIT_VERSION_5_1
。
最后,我偶尔不得不求助于一些更骇人听闻的东西来完全模拟用户“鼠标点击”以及通常伴随它的所有 DOM 事件。如果上面没有其他方法,我只会尝试这个(这很复杂,丑陋和脆弱):
WebView *webView = // get web view
DOMElement *el = // find element somehow
id relatedTarget = [(DOMHTMLDocument *)[el ownerDocument] body];
[el dispatchMouseEventType:@"mouseover" clickCount:0 ctrlKey:NO altKey:NO shiftKey:NO metaKey:NO button:0 relatedTarget:relatedTarget webView:webView];
[el dispatchMouseEventType:@"mousemove" clickCount:0 ctrlKey:NO altKey:NO shiftKey:NO metaKey:NO button:0 relatedTarget:nil webView:webView];
[el dispatchMouseEventType:@"mousedown" clickCount:1 ctrlKey:NO altKey:NO shiftKey:NO metaKey:NO button:0 relatedTarget:nil webView:webView];
[el dispatchMouseEventType:@"click" clickCount:1 ctrlKey:NO altKey:NO shiftKey:NO metaKey:NO button:0 relatedTarget:nil webView:webView];
[el dispatchMouseEventType:@"mouseup" clickCount:1 ctrlKey:NO altKey:NO shiftKey:NO metaKey:NO button:0 relatedTarget:nil webView:webView];
[el dispatchMouseEventType:@"mousemove" clickCount:0 ctrlKey:NO altKey:NO shiftKey:NO metaKey:NO button:0 relatedTarget:nil webView:webView];
[el dispatchMouseEventType:@"mouseout" clickCount:0 ctrlKey:NO altKey:NO shiftKey:NO metaKey:NO button:0 relatedTarget:relatedTarget webView:webView];
我在 Google Code 上的开源项目TDAppKit中有很多这样的代码。