[英]Passing obj-c class to javascript doesn't work. What am I doing wrong?
I'm writing some backend code in javascript and plan to use native code for GUI. 我正在用javascript编写一些后端代码,并计划将本机代码用于GUI。 This works totally fine in Android, but I'm having some issues making this work in Cocoa on Mac OS X. I've followed apples tutorial on the matter, but it just doesn't work.
在Android上,这完全可以正常工作,但是在Mac OS X上的Cocoa中,使它无法正常工作时,我遇到了一些问题。我已经按照Apple的教程进行了操作,但这是行不通的。 Let me try to explain this after you've seen the code.
看完代码后,让我尝试解释一下。
Index.html 的index.html
<html>
<head>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", ready, false);
function ready() {
document.write(returnString());
bridge.onBackendReady();
}
function returnString() {
return "Hello World!!!!";
}
</script>
</head>
<body>
</body>
</html>
AppDelegate.m AppDelegate.m
#import "AppDelegate.h"
#import "BackendBridge.h"
@implementation AppDelegate
@synthesize webview;
@synthesize backend;
-(void)applicationDidFinishLaunching:(NSNotification *)notification
{
backend = [[BackendBridge alloc] init];
NSString *backendPath = [[NSBundle mainBundle] pathForResource:@"Index" ofType:@"html"];
NSURL *backendUrl = [NSURL fileURLWithPath:backendPath];
[[webview mainFrame] loadRequest:[NSURLRequest requestWithURL:backendUrl]];
[[webview windowScriptObject] setValue:backend forKey:@"bridge"];
}
@end
BackendBridge.m BackendBridge.m
#import "BackendBridge.h"
@implementation BackendBridge
-(void)onBackendReady
{
NSLog(@"Ready");
}
@end
So, what I'm trying to do here is rather simple. 所以,我在这里要做的很简单。 Call the function onBackendReady in the BackendBridge class from javascript.
从javascript调用BackendBridge类中的onBackendReady函数。 From what I can understand from apples WebView api and tutorial, this should be the correct way to do it, but it doesn't work (the NSLog call doesnt run).
从我从Apple WebView api和教程中了解的内容来看,这应该是正确的方法,但是它不起作用(NSLog调用不会运行)。 I know that the javascript function works as intended, as in my ui I can see the string "Hello World!!!!"...
我知道javascript函数可以按预期工作,因为在我的ui中,我可以看到字符串“ Hello World !!!!” ...
The comments in WebScriptObject.h
say: WebScriptObject.h
的注释说:
By default, no properties or functions are exported. A class must implement
+isKeyExcludedFromWebScript: and/or +isSelectorExcludedFromWebScript: to
expose selected properties and methods, respectively, to JavaScript.
Maybe add this to BackendBridge
: 也许将其添加到
BackendBridge
:
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)selector
{
return selector != @selector(onBackendReady);
}
bridge_onBackendReady(); bridge_onBackendReady();
Use underscores instead of . 使用下划线代替。 or :
要么 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.