2012-03-03 11 views
0

私はiPhoneのwebappで作業していますが、JavaScriptからネイティブメソッドを呼び出す際に問題があります。JavaScript関数のUIWebViewへの注入

私はwindow.locationを使用して、ネイティブメソッドを呼び出していますし、shouldStartLoadWithRequestに私が必要とされ、その後、私はに基づいて[webView stringByEvaluatingJavaScriptFromString:userId];

を使用して、その値を送信しますどの値を見つけることができるように私は、私のviewControllerクラスである値を必要としますこの値、私はネイティブコードでWebサービスを呼び出す必要があります。今回はshouldStartLoadWithRequestが発砲していません。 つまり、単純に「JS - >ネイティブ - > JS - >ネイティブ」この場合、WebViewデリゲートは起動しません。

私にこれを解決してください。

+0

コードを投稿できますか?おそらく 'webView'デリゲートで? – HelmiB

答えて

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、体内のに、あなたはwebView開始後に起動しますonload()を、持っている必要があります。

<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"); 
} 
関連する問題