2012-03-03 80 views
0

我正在使用iPhone中的web应用程序,并且从JavaScript调用本机方法时遇到问题。将JavaScript函数注入到UIWebView中不能正常工作

我需要一个值,这是我的viewController类,这样,我就用window.locationshouldStartLoadWithRequest我能找到需要它的值,然后调用本地方法,我会用发送值基于[webView stringByEvaluatingJavaScriptFromString:userId];

这个值,我需要在本地代码中调用Web服务。这一次shouldStartLoadWithRequest没有开火。 即简单“JS - > Native - > JS - > Native”在这种情况下,webView委托不会触发。

您能否给我一个解决方案。

+0

你能发表一些代码吗?也许在'webView'委托? – HelmiB 2012-03-03 13:00:34

回答

2

正在运行web.html存储在资源中。

web.html,身体
NSString *path = [[NSBundle mainBundle] pathForResource:@"web" ofType:@"html"]; 
    NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 

    [webView stringByEvaluatingJavaScriptFromString:jsCode]; 
    [webView setDelegate:self]; 
    [webView loadHTMLString:jsCode baseURL:nil]; 

,你应该有onload(),之后webView启动将火。

<html> <body> <head> 

<script> 

function anyFunction(){ 
    window.location='testing123'; 
} 

</script> 

</head><body onload="anyFunction();"> 
</body></html> 

从那里,你应该可以抓住“testing123”。

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType 
{ 
    NSString *data = [[[request URL] absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
    if ([data isEqualToString:@"testing123"]) 
     NSLog(@"value received"); 
}