我正在使用WKWebview来运行javascript脚本。
我没有使用JSContext et.al,因为我需要javascript上下文才能执行单独使用JSContext无法实现的XHTTP请求。
此视图未添加到视图层次结构中,我没有兴趣这样做。
WKWebview仅用于在其引擎中运行JS代码的能力。
javascript代码在模拟器上完全按预期工作。
完全相同的代码也适用于我测试过的某些其他应用程序。
但由于某些原因,在某些应用程序中,除非将WKWebview添加到视图层次结构中,否则WKWebview将不会执行javascript。以下代码将按预期工作。如果删除#warning代码,则停止按预期工作
-(void)connect {
//TODO: Handle multiple connect calls
WKUserContentController *userContentController = [WKUserContentController new];
[self addScriptMessageHandlersForSocketEvents:userContentController];
NSString *socketFileContent = [self.class socketIOScript];
WKUserScript *socketIOScript = [[WKUserScript alloc] initWithSource:socketFileContent
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController addUserScript:socketIOScript];
NSString *bridgeJs = [self.class bridgeScript];
WKUserScript *bridgeScript = [[WKUserScript alloc] initWithSource:bridgeJs
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:NO];
[userContentController addUserScript:bridgeScript];
NSMutableDictionary *d = [NSMutableDictionary new];
for (NSURLQueryItem *item in _parameters) {
d[item.name] = item.value;
}
NSString *params = json(d);
NSString *socketURLScript = [NSString stringWithFormat:@"createSocket(%@,%@);log('created script')",stringify(_url),params];
WKUserScript *createSocket = [[WKUserScript alloc] initWithSource:socketURLScript
injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
forMainFrameOnly:NO];
[userContentController addUserScript:createSocket];
WKWebViewConfiguration * wkconfiguration = [WKWebViewConfiguration new];
wkconfiguration.userContentController = userContentController;
_wv = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:wkconfiguration];
#warning REMOVE THIS AND THE WKWebview stops working on some devices (NOT ALL DEVICES) and works in some applications as expected
[[UIApplication sharedApplication].keyWindow addSubview:_wv];
// END REMOVE THIS
_wv.navigationDelegate = self;
dispatch_group_enter(_loadedSemaphore);
[_wv loadHTMLString:@"<h1></h1>" baseURL:nil];
}
答案 0 :(得分:0)
你实现了WKWebView的所有委托方法吗?