views:

377

answers:

3

I understand to do this on the iPhone you need to trap link requests (as per my other iPhone question UIWebView Expose JavaScript) and you can easily do the reverse and access JavaScript from Obj-C code.

However, I would like to have JavaScript be able to call some Objective-C functions that would somehow be registered with WebKit. I assume that you can do this better than trapping links like on the iPhone as on Mac OS X we have access to the full WebKit.

I wish to basically do the reverse of Using JavaScript from Objective-C

Update: For example is it possible to expose the objective-c method in JavaScript like self.external.objcmethod();

A: 

You can browse to "javascript:my_method()" and intercept the loading...

Look at UIWebViewDelegate delegate.

Documentation at http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebViewDelegate_Protocol/Reference/Reference.html

Look at the method shouldStartLoadWithRequest
((BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType)

Addtionally, you may want to look at https://dev.mobileread.com/trac/webkitbrowser/browser/trunk/WebKit-r30377/WebKit/qt/Api/qwebframe.cpp#L167

MasterGaurav
You're answering for the iPhone. The questioner is asking for Mac OS X.
Peter Hosey
AFAIK, WebKit remains same... infact, trimmed out (a sub-set) for iPhone
MasterGaurav
Thank you. I was asking in the question if there was a better way than the iPhone trapping link requests though.
Luke
I thought there might be a way to setup a custom JavaScript object and functions like in JavaScript, self.external.objcfunction();
Luke
You need to use the WebScripting protocol. See my answer.
Rob Keniger
A: 

The way I've done this in the past is to implement my own URL scheme. In your HTML pages, you'd create links like myapp://dosomefunction?aParameter=aValue. Mac OS X will open your application (if it's not already running) and pass it the URL when you click these links. It's slightly more convenient than trapping requests, and it would work with any web view anywhere on the system.

See the accepted answer to this question for details on how to set up the handler. Unfortunately, this is a one-way operation. You won't be able to get any return values back from the application.

Alex
+2  A: 

Have a look at my answer to this question, which is very similar. I provide code that shows you exactly how to do what you want.

Essentially, you need to implement the WebScripting protocol as per the documentation.

You don't need to define your own URL scheme handler, that is only necessary for iPhone applications. On the Mac the WebView object is many orders of magnitude more powerful than UIWebView on the iPhone and allows full bridging from JavaScript to Objective-C and vice versa.

Rob Keniger
Thank you, this is exactly what I was looking for!
Luke