Exposing Cocoa Object for JS Scripting Environment via WebScriptObject

I see there are several similar questions, but this is a little more thorough.

I am trying to open a simple Cocoa object through WebScriptObject for WebView, hoping the page will send messages to the Cocoa object. The documentation on this is very clear, but for some reason I cannot get it to work. Wonder if you look ...

Here is the object that I upload to 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 load this object into the frameLoad WebView delegate using:

 - (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'm 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: The result of the expression 'client.test' [undefined] is not a function.

A few things. I know that the object is loaded into the scripting environment properly, because it will not pass the conditional plus, I see the description with:

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

But I just don’t know how to properly expose my Cocoa methods. Looking at what I said above, is there any problem with the way I implement methods in my class or call them in JS?

Thanks in advance, Alec

+4
source share
1 answer

It was right in the docs. :(

You must implement + (BOOL) isSelectorExcludedFromWebScript: (SEL) aSelector for the object you are passing.

So, in my case, I had to write

 + (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector { if (aSelector == @selector(test)) return NO; return YES; } 
+2
source

All Articles