Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

aruns1

macrumors newbie
Original poster
Mar 26, 2012
2
0
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.
 
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
 
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
Code:
#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:-
Code:
<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.
 
Last edited by a moderator:
Try calling studentsInClass_ on myrecord in your JavaScript, rather than treating it as a global method.

-Lee
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.