Search code examples
javascriptobjective-ccocoawebviewnsstring

Call a variable NSString from JavaScript in Objective-C


I would like to catch a variable NSString from JavaScript in a WebView.
In this case, the variable will be the path to the application.


My code

 - (NSString *)pathBundle {
    return [[NSBundle mainBundle] bundlePath];
 }

+ (BOOL)isSelectorExcludedFromWebScript:(SEL)selector { return NO; }
+ (BOOL)isKeyExcludedFromWebScript:(const char*)name { return YES; }

Now, I try to call this in JavaScript with alert(app.pathBundle_); but the alert message says undefined.

I already managed to implement a Objective-C function to change window title via JavaScript (- (void)changeTitle:(NSString *)Value { ... }), but with the NSString the result doesn't seem to pass from Cocoa to JS.

May someone have an idea of what I'm doing wrong?


Solution

  • I just found a solution. Here is my working code:

    - (NSString *)pathBundle:(NSString *)Value {
        return [[NSBundle mainBundle] bundlePath];
    }
    
    - (NSString *)pathResources:(NSString *)Value {
        return [[NSBundle mainBundle] resourcePath];
    }
    

    And in JavaScript, I call it like that:

    alert(Stz.pathBundle_());
    alert(Stz.pathResources_());