4

I see there are a couple of similar questions, but this is a bit more basic.

I am trying to expose a simple Cocoa object via WebScriptObject to a WebView, hopefully allowing the page to send messages to the Cocoa object. The documentation on this is very clear, but for some reason I can't get it to work. Wondering if you'll have a look...

Here is the Object that I'm loading into the scripting environment.

@interface Client : NSObject {

     NSString *test;

}

@implementation Client

- (id)init {

    self = [super init];
    test = [[NSString alloc] initWithString:@"Hey Simon"];
    return self;

}

- (NSString *)test {

    return test;
}

Then I'm loading that object in the WebView's frameLoad delegate, with:

- (void)webView:(WebView *)webView didClearWindowObject:(WebScriptObject *)windowObject forFrame:(WebFrame *)frame {

    Client *_client = [[Client alloc] init];
    [windowObject setValue:_client forKey:@"client"];

}

On the JS side of things, I am just doing something really basic:

if( 'client' in window ) {

var client = window.client;

console.log( '---' );

console.log( 'client.test(): ' + client.test() );

console.log( '---' );

}

The JS console says TypeError: Result of expression 'client.test' [undefined] is not a function.

A couple of things. I know the object is being loaded into the scripting environment properly because it wouldn't pass the conditional plus I can see a description with:

console.log( 'Client object: ' + client )

But I just don't know how to expose my cocoa methods properly. Looking at what I've said above, is there some problem with how I am implementing the methods in my class, or calling them in JS?

Thanks in advance, Alec

0

1 Answer 1

2

It was right there in the docs. :(

You have to implement + (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector on the object you are passing in.

So in my case, I had to write

+ (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector

{
    if (aSelector == @selector(test)) return NO;
    return YES;
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.