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.

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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;"
Just posted the solution I used. Thanks for your help.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.