如何在 iOS 上停止 JavaScriptCore JSContext 强制评估?



有时应该强制停止正在评估的脚本,但我找不到实现此目的的方法。有人指出JSContextGroupSetExecutionTimeLimit可能有效,但在我的测试中没有,有人可以帮忙吗?

另一个参考:https://github.com/phoboslab/JavaScriptCore-iOS/issues/14

我的代码:

int extendTerminateCallbackCalled = 0;
static bool extendTerminateCallback(JSContextRef ctx, void *context)
{
extendTerminateCallbackCalled++;
if (extendTerminateCallbackCalled == 2) {
JSContextGroupRef contextGroup = JSContextGetGroup(ctx);
JSContextGroupSetExecutionTimeLimit(contextGroup, .200f, extendTerminateCallback, 0);
return false;
}
return true;
}
+ (void)stop
{
JSGlobalContextRef ref = [_context JSGlobalContextRef];
JSContextGroupRef contextGroup = JSContextGetGroup(ref);
JSContextGroupSetExecutionTimeLimit(contextGroup, .200f, extendTerminateCallback, 0);
}

这是一个可能的方法的想法

+ (void)stop
{
JSContext *context = [JSContext currentContext]; // or whichever your
// set property of JS global object to specific know value
// that should be checked inside JS code regularly during
// long operations and interrupt self execution
context[@"externallyCancelled"] = @(YES); 
}

最新更新