RedMitch
RedMitch

Reputation: 151

Call javascript - click() in a WebView from Cocoa Objective-C code

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.

Upvotes: 1

Views: 2332

Answers (2)

RedMitch
RedMitch

Reputation: 151

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.

Upvotes: 1

hooleyhoop
hooleyhoop

Reputation: 9198

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?

Upvotes: 1

Related Questions