1

In a MacOS X application, I create a Window containing a WebView. The WebView is initialized on a html page that contains an anchor: Go To Google.

I would like to click on that link from another class.

It seems clear that a simple javascript code would do the trick: document.getElementById("myLink").click();

So, I wrote that small objective-c code that should do it:

   NSString *cmd = @"document.getElementById(\"myLink\").click();";
    id result = [[attachedWebView windowScriptObject] evaluateWebScript:cmd];
    if ([result isMemberOfClass:[WebUndefined class]]) {
            NSLog(@"evaluation of <%@> returned WebUndefined", cmd)

But I can't make it work. If anybody has an idea, that would really help.

RedMitch
  • 151
  • 1
  • 7

2 Answers2

1

I think it is nothing todo with webview, but just your javascript.

Does it work if you try it in Safari's console? I wouldn't expect it to as you can only click() input elements (buttons) reliably cross-browser. A JQuery click() should work tho.

see How do I programmatically click a link with javascript?

Community
  • 1
  • 1
hooleyhoop
  • 9,128
  • 5
  • 37
  • 58
  • I think you're right. I tested it manualy - and it worked in Firefox 3 using Firebug, but not in Safair - which is WebKit-. And there, I can't make it work. – RedMitch Sep 01 '11 at 19:48
  • so it depends on what you expect the link to do. If you want to follow the link you can execute the javascript "location.href = link.href;" – hooleyhoop Sep 01 '11 at 20:03
  • Just posted the solution I used. Thanks for your help. – RedMitch Sep 01 '11 at 20:14
1

So here is the solution I used.

Created a file: WebAgent.js containing the following code:

function myClick(id) {
    var fireOnThis = document.getElementById(id);
    var evObj = document.createEvent('MouseEvents');
    evObj.initEvent( 'click', true, true );
    fireOnThis.dispatchEvent(evObj);
}

And the following code in my objective-c class

// load cmd.js
    NSString *path = @"/code/testagent/WebAgent/WebAgent/WebAgent.js";
    NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [[self attachedWebView ]stringByEvaluatingJavaScriptFromString:jsCode];

//do the click
    NSString * anchorId = @"myId";
    NSString *call = [NSString stringWithFormat:@"WebAgent_click('%@')",anchorId];
    [[self attachedWebView] stringByEvaluatingJavaScriptFromString:call];

NB: I used this solution to have the JS code in a specific file, as I expect to have more JS code in the future.

Thanks for your help.

RedMitch
  • 151
  • 1
  • 7