PDA

View Full Version : Objective-C methods from Javascript in Cocoa




aruns1
Mar 27, 2012, 01:09 AM
Hello!
I have a webview control in a Cocoa application where I am showing a web page. I need to access Objective-C method from Javascript in HTML page shown in Webview. I have tried "Calling Objective-C Methods From JavaScript"
from apple site "https://developer.apple.com/library/mac/#documentation/appleapplications/Conceptual/SafariJSProgTopics/Tasks/ObjCFromJavaScript.html". But it did not worked. Pleases help me to Call Objective-C methods from Javascript.



lee1210
Mar 27, 2012, 01:52 AM
The document from your post looks like it should get you where you're wanting to go. Post your code and tell us what happens. Is your exposed object undefined in javascript? Is it defined, but the methods you expect are not? Are the methods defined but there is some failure when you try to call them?

Post your code and a more complete description of its behavior and we'll be glad to help.

-Lee

aruns1
Mar 27, 2012, 02:35 AM
The document from your post looks like it should get you where you're wanting to go. Post your code and tell us what happens. Is your exposed object undefined in javascript? Is it defined, but the methods you expect are not? Are the methods defined but there is some failure when you try to call them?

Post your code and a more complete description of its behavior and we'll be glad to help.

-Lee

I have a class ObjCMethods as below

#import "ObjCMethods.h"

@implementation ObjCMethods

- (int)studentsInClass:(int)standard;
{
return 20;
}
@end
with just one method as above.

Also I am displaying an html page in webview as below:-

#import "Controller.h"
#import "ObjCMethods.h"
#import <WebKit/WebKit.h>

@implementation Controller
-(void)awakeFromNib
{


[[_webView mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"/Users/abcd/Desktop/sample.html"]]];
ObjCMethods *record1 = [[ObjCMethods alloc] init];



id win = [_webView windowScriptObject];

[win setValue:record1 forKey:@"ObjCMethods"];
}

@end

_webview is outlet to Webview in the xib file.

The code for html page is as below:-

<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
var myrecord = window.ObjCMethods;
var studentsCount = studentsInClass_(5);
document.write(studentsCount);
</script>
</body>
</html>


I expect output to be
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5
20
But at bootom 20 is missing from the original output showing that Objective-C method is not being called.

lee1210
Mar 27, 2012, 06:31 PM
Try calling studentsInClass_ on myrecord in your JavaScript, rather than treating it as a global method.

-Lee