WKWebView:从需要Basic Auth的远程URL使用evaluateJavaScript时遇到麻烦

时间:2015-11-17 00:29:02

标签: ios objective-c authorization wkwebview javascript-injection

我有一个远程JavaScript文件,我想从WKWebView加载。 JavaScript文件所在的开发网站需要基本身份验证才能访问。 需要加载JavaScript文件作为按钮的结果。 换句话说,我不能使用WKUserScript injectionTime选项。

我有两个代码示例。他们俩都只工作了一半。我无法测试auth是否在没有EvaluateJavascript工作的情况下工作,并且我无法在没有Basic Auth工作的情况下测试EvaluateJavascript函数......所以...使用WKWebView * webView ...

NSString *authStr = @"username:password";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];

NSURL* jsURL = [NSURL URLWithString:@"http://dev.xxxx.com/js/xxxxx.js"];

NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:jsURL];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];

[_webView loadRequest:request];

我可以在webView窗口中看到javascript,但它没有被评估。

然后我有另外一个策略:

     - (void)handleButton {
            NSURL* jsURL = [NSURL URLWithString:@"http://dev.xxxx.com/js/xxxxx.js"];
            _scriptString = [NSString stringWithContentsOfURL:jsURL usedEncoding:NSUTF8StringEncoding error:nil];
        }

-(void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{
    if (challenge.previousFailureCount == 0){
        NSURLCredentialPersistence persistence = NSURLCredentialPersistenceForSession;
        NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:persistence];
        completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
        NSLog(@"in Auth");
    }
    else{
        NSLog(@"%s: challenge.error = %@", __FUNCTION__, challenge.error);
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
     NSLog(@"navigation complete");
    NSLog(@"scriptString %@", _scriptString); //Says UNAUTHORIZED
    if ([_scriptString length] > 0) {

        [_webView evaluateJavaScript:_scriptString completionHandler:^(NSString *result, NSError *evaluateError) {
            if (result == nil) {
                NSLog(@"no go dude: %@", evaluateError);
                return;
            }
            NSData *data = [result dataUsingEncoding:NSUTF8StringEncoding];
            NSLog(@"i think it worked: @%", data);

        }];
    }

}

非常感谢任何帮助!!

1 个答案:

答案 0 :(得分:0)

我在iPhone上的Safari中加载了javascript URL,并在弹出窗口中输入了基本的auth用户名和密码。 然后,这是有效的代码:

NSURL *jsURL = [NSURL URLWithString:@"http://username:password@dev.xxxx.com/js/xxxxxx.js"];
    NSString *injectedJS = [NSString stringWithContentsOfURL:jsURL encoding:NSUTF8StringEncoding error:nil];

    [_webView evaluateJavaScript:injectedJS completionHandler:nil];