在 iOS 中使用 JSContextGroupSetExecutionTimeLimit

Using JSContextGroupSetExecutionTimeLimit in iOS

我需要在 JSContext object 中停止执行 Javascript?我发现以下方法正是我需要的

@function
@abstract Sets the script execution time limit.
@param group The JavaScript context group that this time limit applies to.
@param limit The time limit of allowed script execution time in seconds.
@param callback The callback function that will be invoked when the time limit
 has been reached. This will give you a chance to decide if you want to
 terminate the script or not. If you pass a NULL callback, the script will be
 terminated unconditionally when the time limit has been reached.
@param context User data that you can provide to be passed back to you
 in your callback.

 In order to guarantee that the execution time limit will take effect, you will
 need to call JSContextGroupSetExecutionTimeLimit before you start executing
 any scripts.
*/
JS_EXPORT void JSContextGroupSetExecutionTimeLimit(JSContextGroupRef, double limit, JSShouldTerminateCallback, void* context) AVAILABLE_IN_WEBKIT_VERSION_4_0;

不幸的是,该方法没有详细记录,我不知道如何使用它。

我的密码是

JSContextGroupRef group = JSContextGroupCreate();
JSGlobalContextRef context = JSGlobalContextCreateInGroup(group, NULL);
NSString *code = @"while(1){}";
JSStringRef script = JSStringCreateWithCFString((__bridge CFStringRef)code);
JSContextGroupSetExecutionTimeLimit(group,.200f,nil,0);
JSValueRef error = NULL;
JSValueRef value = JSEvaluateScript(context, script, NULL, NULL, 0, &error);

当我尝试调用 JSContextGroupSetExecutionTimeLimit 时出现编译错误。

Implicit declaration of function "JSContextGroupSetExecutionTimeLimit" is invalid in C99,

似乎调用来自 JSContextRefPrivate.h,问题是如何将此 header 添加到我的项目中以及实现在哪里。

任何建议我该如何处理。谢谢

这实际上很简单:只需将相关函数的声明(和 JSShouldTerminateCallback typedef)复制到您的源代码中。这告诉编译器函数在运行时可用的确切签名。

由于 JavascriptCore 是开源 WebKit 项目的一部分,函数声明甚至在 WebKit repository 中都有有用的描述。相关部分是:

typedef bool
(*JSShouldTerminateCallback) (JSContextRef ctx, void* context);

JS_EXPORT void JSContextGroupSetExecutionTimeLimit(JSContextGroupRef group,
                                                   double limit, JSShouldTerminateCallback callback, void* context) CF_AVAILABLE(10_6, 7_0);

JS_EXPORT void JSContextGroupClearExecutionTimeLimit(JSContextGroupRef group) CF_AVAILABLE(10_6, 7_0);

此外,您不必像 JavascriptCore documentation, every JSContextRef you create is assigned a new JSContextGroup. You can get the group of a context using the public JSContextGetGroup 功能那样自己创建群组。

WebKit tests.

中提供了使用私有 JSContextGroupSetExecutionTimeLimit API 的示例

重要提示:如前所述,使用此私有 API 的应用可能会被 App Store 拒绝。