1. 程式人生 > >iOS 10.3 wkwebview WKUserScript 無法成功注入本地js檔案的問題

iOS 10.3 wkwebview WKUserScript 無法成功注入本地js檔案的問題

NSString *runtimejs = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"runtime" ofType:@".js"] encoding:NSUTF8StringEncoding error:nil];
    NSString *vpimjs = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"browser-bundle" ofType:@".js"] encoding:NSUTF8StringEncoding error:nil];
    NSString *jsall = [NSString stringWithFormat:@"%@ %@", runtimejs, vpimjs];
    WKUserScript *script = [[WKUserScript alloc] initWithSource:jsall injectionTime:(WKUserScriptInjectionTimeAtDocumentStart) forMainFrameOnly:YES];
    
    WKUserContentController *userContent = [[WKUserContentController alloc] init];
    [userContent addUserScript:script];
    [userContent addScriptMessageHandler:self name:@"NativeMethod"];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    [configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
    [configuration setUserContentController:userContent];
    
    self.web = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) configuration:configuration];
    
    NSString *htmlpath = [[NSBundle mainBundle] pathForResource:@"local" ofType:@".html"];
    NSString *localhtml = [NSString stringWithContentsOfFile:htmlpath encoding:NSUTF8StringEncoding error:nil];
    [self.web loadHTMLString:localhtml baseURL:[NSURL fileURLWithPath:htmlpath isDirectory:YES]];
    
    self.web.UIDelegate = self;
    self.web.navigationDelegate = self;
    [self.view addSubview:self.web];
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=TypeError: undefined is not an object (evaluating 'window.VPIM.default'), WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred, WKJavaScriptExceptionColumnNumber=30}

根據Safari連調js檔案根本沒有注入進去,  在11上正確注入,徵集擼友指點回復~!