2011-07-11 14 views
7

estoy tratando de llamar a una función JavaScript desde un archivo HTML local cargada en UIWebView pero deosn't responderstringByEvaluatingJavaScriptFromString no funciona

se vea así

NSString *script=[NSString stringWithFormat:@"sample()"]; 

if (tekst.loading) { 
    NSLog(@"Loading"); 
} else { 
    NSLog(@"Fully loaded"); 
    [tekst stringByEvaluatingJavaScriptFromString:script]; 
} 

y en html

<head> 
.... 
<script type='text/javascript'> 
function sample() { 
alert('Paznja'); 
} 
</script> 
... 
</head> 
+1

Sin relación con su pregunta, pero no hay necesidad de llamar 'stringWithFormat:' aquí. Simplemente asigne el literal de cadena directamente: NSString * script = @ "sample()"; – highlycaffeinated

Respuesta

13

Me parece que no está utilizando un delegado en su UIWebView. Si se establece un delegado y poner la llamada al Javascript en el "- (void) webViewDidFinishLoad: (UIWebView *) web View" método, que funciona bien:

UIWebView *wv = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, 700.0, 700.0)]; 
[self.view addSubview:wv]; 
wv.delegate = self; 
[wv loadHTMLString:@"<html><head><script type='text/javascript'>function sample() {alert('Paznja');}</script></head><body><h1>TEST</h1></body></html>" baseURL:nil]; 
[wv release]; 

y en la misma clase:

- (void)webViewDidFinishLoad:(UIWebView *)webView { 
    [webView stringByEvaluatingJavaScriptFromString:@"sample()"]; 
} 

Cuando ejecuto este código, el mensaje de alerta funciona bien.

+0

¡Obviamente! agradable ... gracias, me salvó el día. – Lukasz

0

nota adicional, si usted está esperando un objeto detrás de la función de JavaScript en lugar de una cadena a continuación, hacer lo siguiente:

NSString *json = [self.webView stringByEvaluatingJavaScriptFromString:@"JSON.stringify(TestMethod())"];