xcode JavaScriptCore console.log

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19649932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 04:13:13  来源:igfitidea点击:

JavaScriptCore console.log

javascriptobjective-cxcodemacoscore-foundation

提问by SheetJS

I've put together a very simple program that uses JavaScriptCore to evaluate JS:

我已经编写了一个非常简单的程序,它使用 JavaScriptCore 来评估 JS:

#import <CoreFoundation/CoreFoundation.h>
#import <JavaScriptCore/JavaScriptCore.h>

int main(int argc, const char * argv[])
{
    JSGlobalContextRef ctx = JSGlobalContextCreate(NULL);

    FILE *f = fopen(argv[1],"r");
    char * buffer = malloc(10000000);
    fread(buffer,1,10000000,f);

    CFStringRef strs = CFStringCreateWithCString(NULL, buffer, kCFStringEncodingASCII);

    JSStringRef jsstr = JSStringCreateWithCFString(strs);
    JSValueRef result = JSEvaluateScript(ctx, jsstr, NULL, NULL, 0, NULL);

    double res  = JSValueToNumber(ctx, result, NULL);
    JSGlobalContextRelease(ctx);

    printf("%lf\n", res);
    return 0;
}

The idea here is that the last value is expected to be a Number, and that value is printed. This works for valid javascript code, such as

这里的想法是最后一个值应该是 a Number,然后打印该值。这适用于有效的 javascript 代码,例如

var square = function(x) { return x*x; }; square(4)

However, if the code tries to perform a console.log, the program segfaults. Is there a log function available in JSC or do I have to roll my own?

但是,如果代码尝试执行 a console.log,则程序会出现段错误。JSC 中是否有可用的日志功能,还是我必须自己推出?

采纳答案by Mike

You do have to provide your own console log if using the JavaScriptCore framework from Mac or IOS.

如果使用 Mac 或 IOS 的 JavaScriptCore 框架,则必须提供自己的控制台日志。

Here is some code that worked for me (sorry it is Objective-C rather than standard C as per your code above):

这是一些对我有用的代码(抱歉,按照上面的代码,它是 Objective-C 而不是标准 C):

JSContext *javascriptContext  = [[JSContext alloc] init];
javascriptContext[@"consoleLog"] = ^(NSString *message) {
    NSLog(@"Javascript log: %@",message);
};

Then you use it from Javascript by:

然后您通过以下方式从 Javascript 中使用它:

consoleLog("My debug message");

Note that I have tried to define a vararg version (log taking multiple parameters) but I couldn't get this to work correctly across the framework api.

请注意,我试图定义一个可变参数版本(日志采用多个参数),但我无法让它在框架 api 中正常工作。

Note that this solution uses features introduced with the new Objective-C API for the JavaScriptCore.framework introduced at the same time as IOS 7. If you are looking for an intro to this well-integrated bridge between Objective-C and Javascript, check out the 2013 WWDC introduction "Integrating JavaScript into Native Apps" session on Apple's developer network: https://developer.apple.com/videos/wwdc/2013/?id=615

请注意,此解决方案使用了与 IOS 7 同时引入的 JavaScriptCore.framework 的新 Objective-C API 引入的功能。如果您正在寻找有关 Objective-C 和 Javascript 之间良好集成桥梁的介绍,请查看Apple 开发者网络上的 2013 年 WWDC 介绍“将 JavaScript 集成到本机应用程序”会议:https: //developer.apple.com/videos/wwdc/2013/?id=615

Update to answer:

更新回答:

For those of you wanting to maximise your javascript code reuse without refactoring, I've managed to get a version working that declares a log of the form console.log():

对于那些希望在不重构的情况下最大限度地重用 javascript 代码的人,我设法使一个版本可以正常工作,该版本声明了表单console.log()的日志:

JSContext *javascriptContext  = [[JSContext alloc] init];
[javascriptContext evaluateScript:@"var console = {}"];
javascriptContext[@"console"][@"log"] = ^(NSString *message) {
    NSLog(@"Javascript log: %@",message);
};

Then you use it from Javascript by:

然后您通过以下方式从 Javascript 中使用它:

console.log("My debug message");

回答by AlBeebe

Swift 3.0

斯威夫特 3.0

let javascriptContext = JSContext()
javascriptContext?.evaluateScript("var console = { log: function(message) { _consoleLog(message) } }")
let consoleLog: @convention(block) (String) -> Void = { message in
    print("console.log: " + message)
}
javascriptContext?.setObject(unsafeBitCast(consoleLog, to: AnyObject.self), forKeyedSubscript: "_consoleLog" as (NSCopying & NSObjectProtocol)!)

Swift 2.1

斯威夫特 2.1

let javascriptContext = JSContext()
javascriptContext.evaluateScript("var console = { log: function(message) { _consoleLog(message) } }")
let consoleLog: @convention(block) String -> Void = { message in
    print("console.log: " + message)
}
javascriptContext.setObject(unsafeBitCast(consoleLog, AnyObject.self), forKeyedSubscript: "_consoleLog")

Then you use it from Javascript by:

然后您通过以下方式从 Javascript 中使用它:

console.log("My debug message");

回答by Anton Belousov

self.jsContext = JSContext()
self.jsContext.evaluateScript(...)       
let logFunction: @convention(block) (String) -> Void  = { (string: String) in
    print(string)
}

self.jsContext.setObject(logFunction, forKeyedSubscript: "consoleLog" as NSCopying & NSObjectProtocol)

回答by Rakesh Yembaram

You can debug JS file attached to context in Safari.

您可以在 Safari 中调试附加到上下文的 JS 文件。

Steps:

脚步:

1) Start Safari

1) 启动 Safari

2) In Safari, enable the Develop menu by going to "Preferences" -> "Advanced" -> "Show Develop menu in menu bar"

2) 在 Safari 中,通过转到“首选项”->“高级”->“在菜单栏中显示开发菜单”启用开发菜单

3) Go to Develop menu -> "Simulator" or name of your computer -> select "Automatically show web inspector for JSContexts" and "Automatically pause connecting to JSContexts"

3) 转到开发菜单 -> “模拟器”或您的计算机名称 -> 选择“自动显示 JSContexts 的 Web 检查器”和“自动暂停连接到 JSContexts”

4) Re-run your project and Safari should auto-show the web inspector

4) 重新运行你的项目,Safari 应该会自动显示 web 检查器