将JavaScript函数注入UIWebView始终不起作用

时间:2012-03-03 11:31:11

标签: javascript iphone uiwebview

我正在使用iPhone中的webapp,我遇到了从JavaScript调用本机方法的问题。

我需要一个在viewController类中的值,以便我使用window.location调用本机方法,在shouldStartLoadWithRequest我可以找到需要的值然后我会发送使用[webView stringByEvaluatingJavaScriptFromString:userId];

表示该值

基于此值,我需要使用本机代码调用Web服务。这次shouldStartLoadWithRequest没有被解雇。 即只是 " JS - >原生 - > JS - > Native" 在这种情况下webView委托不会触发。

请你帮我解决一下。

1 个答案:

答案 0 :(得分:2)

运行存储在资源中的 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];

web.html 中,在正文中,您应该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");
}