Search code examples
iosobjective-cjavascriptcore

How to assign a class to a variable with JavascriptCore


I'm trying to use JavascriptCore framework for iOS but I'm facing a problem.

My simple javascript text :

NSString * jsCode = @"var log = require('log'); log.test();";

My Obj-c code :

JSContext * context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];

context[@"require"] = ^(NSString* sting) {
    NSLog(@"require ok");
    return [JsLogFacade class];
};

[context evaluateScript:jsCode];

All I want to do, is assign my JsLog class to the log variable in my javascript so I can evaluate log.test() after.

JsLogFacade.h

#import <Foundation/Foundation.h>
#import <JavaScriptCore/JSExport.h>

@protocol LogJsExports<JSExport>
+ (void) test;
@end

@interface JsLogFacade : NSObject <LogJsExports>
@end

JsLogFacade.m

#import "JsLogFacade.h"

@implementation JsLogFacade
+ (void) test {
    NSLog(@"It's working");
}
@end

I've got no error but I don't see my NSLog. Note that if I remove my return statement inside my block, "require ok" works.

PS : I can't just do the code below because I'll have no idea what is the code inside my script at the end

context[@"log"]=[JsLogFacade class];

Do you have any idea why or even if what I'm trying to do is possible ?


Solution

  • Should you not be assigning the context entry as an instance of your logger? As in:

    context[@"log"]=[[JsLogFacade alloc] init];
    

    or returning an instance rather than a class in your require code?

    And should the function test not be an instance method as opposed to a class method?

    @implementation JsLogFacade
    - (void) test 
    {
        NSLog(@"It's working");
    }
    @end