将obj-c类传递给javascript;不起作用.我做错了什么

Passing obj-c class to javascript doesn't work. What am I doing wrong?

本文关键字:不起作用 错了 什么 javascript obj-c      更新时间:2023-09-26

我正在用javascript编写一些后端代码,并计划为GUI使用本机代码。这在安卓系统中运行得很好,但我在Mac OS X上的Cocoa中遇到了一些问题。我已经学习了苹果的教程,但它就是不起作用。让我在你看过代码后解释一下。

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

#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

#import "BackendBridge.h"

@implementation BackendBridge
-(void)onBackendReady
{
NSLog(@"Ready");
}
@end

所以,我想在这里做的很简单。从javascript调用BackendBridge类中的onBackendReady函数。根据我从apples WebView api和教程中了解到的,这应该是正确的方法,但它不起作用(NSLog调用不运行)。我知道javascript函数按预期工作,因为在我的ui中我可以看到字符串"Hello World!!!"。。。

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.

也许可以将此添加到BackendBridge:

+ (BOOL)isSelectorExcludedFromWebScript:(SEL)selector
{
    return selector != @selector(onBackendReady);
}

bridge_onBackendReady();

使用下划线而不是。或: