0

我有这个JavaScript功能:

function extract(html) {
     return html;
}

我想从我的 iPhone 应用程序运行它,所以我创建一个UIWebView并添加它:

        UIWebView *fullJavaScriptWebView = [[UIWebView alloc] init];
        fullJavaScriptWebView.delegate = self;

        NSURL *fileUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"] isDirectory:NO];

        [fullJavaScriptWebView loadRequest:[NSURLRequest requestWithURL:fileUrl]];

在 UIWebViewDelegate 中webViewDidFinishLoad

NSString *html = [self.javaScriptDic objectForKey:@"html"];
NSString *jsCall = [NSString stringWithFormat:@"extract('%@');",html];
NSString *tmp = [webView stringByEvaluatingJavaScriptFromString:jsCall];

每次我运行它时,tmp 都是空的。知道这段代码有什么问题吗?

html是我之前下载的网站的 html,它包括以下字符:“,”......

4

2 回答 2

1

html如果要将 var 传递给 Javascript 函数,则该var 似乎有问题的字符。尝试先对其进行转义:

-(NSString *)scapeForJS:(NSString *)string {
    string = [string stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"];
    string = [string stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    string = [string stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"];
    string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
    string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@"\\r"];
    string = [string stringByReplacingOccurrencesOfString:@"\f" withString:@"\\f"];
    return string;
}
于 2013-07-03T09:45:59.553 回答
0

将 html 字符串加载到 webView 中:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"Untitled" ofType:@"html" inDirectory:nil];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
    [self.webView loadHTMLString:htmlString baseURL:nil];

然后你可以获取内部 html,进行操作并返回结果:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString *result = [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat: @"function f(){ var markup = document.documentElement.innerHTML; return markup;} f();"]];
NSLog(@"result: '%@'", result);
}
于 2013-07-03T10:36:51.133 回答