在Objective-C的WKWebView上评估JavaScript时获取“发生JavaScript异常”

时间:2019-03-06 09:10:01

标签: ios objective-c wkwebview pdfjs pdf-viewer

在这里,我正在使用Reference swift项目在WKWebview的PDFViewer中加载PDF文件。

参考项目-https://github.com/Minitex/PDFJSTest/blob/master/PDFJSTest/ViewController.swift

在参考项目中,用于加载PDF文件的代码如下所示

func openPDFInViewer(myURL: URL)
{
    let pdf = NSData(contentsOf: myURL)

    let length = pdf?.length
    var myArray = [UInt8](repeating: 0, count: length!)
    pdf?.getBytes(&myArray, length: length!)

    webView?.evaluateJavaScript("PDFViewerApplication.open(new Uint8Array(\(myArray)))", completionHandler: { result, error in
        print("Completed Javascript evaluation.")
        print("Result: \(String(describing: result))")
        print("Error: \(String(describing: error))")
   })
}

然后我试图将此函数转换为Objective-C语言,如下所示:

-(void)renderPDF:(NSTimer*)theTimer
{
    NSMutableDictionary *dictData = [[NSMutableDictionary alloc] initWithDictionary:theTimer.userInfo];
    NSURL *requestURL =  (NSURL *)[dictData valueForKey:@"request_url"];

    NSData *data = [NSData dataWithContentsOfURL:requestURL];
    NSUInteger len = [data length];
    uint8_t myArray[len];
    [data getBytes:&myArray length:len];

    NSString *strForEvaluate = [NSString stringWithFormat:@"PDFViewerApplication.open(new Uint8Array('%s'));",myArray];


    [wkWebView evaluateJavaScript:strForEvaluate completionHandler:^(id Result, NSError * _Nullable error) {
        if (error)
        {
            NSLog(@"This is error....%@",error.description);
        }
        else if(Result)
        {
            NSLog(@"%@",Result);
        }
     }];
}

当我尝试运行该应用并评估JavaScript函数时,得到了这样的错误响应

Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=SyntaxError: Unexpected EOF, WKJavaScriptExceptionColumnNumber=0, WKJavaScriptExceptionSourceURL=file:///Users/sapanaranipa/Library/Developer/CoreSimulator/Devices/207FA841-3256-45D2-8698-2B769A72A2F4/data/Containers/Bundle/Application/4BD7E620-DF16-429B-BBC2-2A36BA2A2DE8/SureFox.app//PDF_Web/pdf.js-dist/web/viewer.html, NSLocalizedDescription=A JavaScript exception occurred}

请帮助我,谢谢。

1 个答案:

答案 0 :(得分:1)

您将任意字节数组视为C字符串,并且该字符串不能以空值结尾或包含'之类的东西,这些东西在JavaScript中是不需要的。因此,当您尝试创建字符串时,它也可能会崩溃。

有问题的部分在这里使用%s格式程序:

NSString *strForEvaluate = [NSString stringWithFormat:@"PDFViewerApplication.open(new Uint8Array('%s'));",myArray];

(另外,uint8_t myArray[len];可能会导致大数据堆栈溢出[ha!]。)

您要创建的字符串代表一个JavaScript数字数组,例如[25, 243, 0, 123]。这是一种可行的方法(未经测试):

NSMutableArray<NSString *> *bytes = [NSMutableArray array];
const uint8_t *rawBytes = data.bytes;
for (NSUInteger i = 0; i < data.length; i++) {
    [bytes addObject:[NSString stringWithFormat:@"%d", (int)rawBytes[i]]];
}

NSString *javaScriptArray = [bytes componentsJoinedByString:@","];

NSString *strForEvaluate = [NSString stringWithFormat:
    @"PDFViewerApplication.open(new Uint8Array([%@]));", javaScriptArray];