Reputation: 6315
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();
Upvotes: 3
Views: 4987
Reputation: 46028
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.
Upvotes: 6
Reputation: 26859
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.
Upvotes: 0
Reputation: 9414
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
Upvotes: 0