在我的iPhone应用程序中执行JavaScript

时间:2013-07-03 09:28:10

标签: javascript iphone ios objective-c

我有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,它包括如下字符:“,'.......

2 个答案:

答案 0 :(得分:1)

html var似乎有问题的字符,如果你要将它传递给Javascript函数。试着先看看它:

-(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;
}

答案 1 :(得分: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);
}