Seb123
Seb123

Reputation: 491

Javascript send message to objective-c in Mac cocoa application

I'm fairly new to objective-C so please don't assume I know stuff because I probably won't :).

I have a cocoa application for Mac (not iOS) with a webview. In the webview there is a site which acts as a mini messaging client. When a message is received, I would like javascript to notify objective-c that a message has been received... and objective-c will then run some code such as create a growl popup.

I have looked at WebView Class Reference on the Apple Developer website, however I'm not quite sure how to implement it properly.

Upvotes: 3

Views: 1249

Answers (1)

Vervious
Vervious

Reputation: 5569

What you're looking for is the reference document "Calling Objective-C Methods From Javascript" (reference)

Basically, to summarize it, you have to explicitly expose your Objective-C classes to the javascript scripting environment. The WebScripting informal protocol is the one you want to implement for your custom object to be exposed to be able to do just this.

Once the object you want to expose (e.g. your "Notification object") to javascript implements + (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector; and + (BOOL)isKeyExcludedFromWebScript:(const char *)name; the controller/delegate of your webview should now make the object available to the javascript.

For instance, in the Frame Load Delegate of your webView instance:

- (void)webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)windowObject forFrame:(WebFrame *)frame {
     // Create the Obj-C object you want JS to be able to access
     CustomNotificationCenter *noteCenter = [CustomNotificationCenter sharedNotificationCenter];
     // Get the script object that corresponds to "window" in JS
     id win = [sender windowScriptObject];
     // Add our noteCenter as a property of "window" called "customNotifications"
     [win setValue:noteCenter forKey:@"customNotifications"];
}

And if you've done everything correctly, you should be able to use your Objective-C object in Javascript. For instance, if you've exposed a method named "printNotification:" for your noteCenter, in Javascript this should work:

function messageReceived(messageText) {
     window.customNotifications.printNotification_("Notification!" + messageText);
}

And of course you would use Growl to show the notification in your Custom Obj-C object and the implementation of printNotification. (If you're on Mountain Lion the new Notification Center is amazing, too). Hope that helps.

Upvotes: 4

Related Questions