简体   繁体   中英

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. 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. Let me try to explain this after you've seen the code.

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

So, what I'm trying to do here is rather simple. Call the function onBackendReady in the BackendBridge class from javascript. 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). I know that the javascript function works as intended, as in my ui I can see the string "Hello World!!!!"...

The comments in WebScriptObject.h say:

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 :

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

bridge_onBackendReady();

Use underscores instead of . or :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM