Estoy intentando ejecutar algo de Javascript en el contenido dentro de un UIWebView. Tal vez mi conocimiento del tiempo de ejecución de Javascript es deficiente, pero yo "m confundido sobre el siguiente ejemplo Ver código fuente y comentarios para más detalles:.Confirmación del comportamiento de Javascript en un UIWebView
NSString *html = [NSString stringWithFormat:@"<html><head><script type='text/javascript'>var content='the initial content';function myFunc(){return 'value of content: ' + content;}myFunc();</script></head><body>Hello blank</body></html>"];
// I would expect after this call that the variable content exists, as well as the function myFunc()
[self.webView loadHTMLString:html baseURL:nil];
// However, it appears not to. The following call returns nothing
NSString *result = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunc();"];
NSLog(@"result: %@", result);
// Inserting the Javascript at this point seems to work as expected
result = [self.webView stringByEvaluatingJavaScriptFromString:@"var content='the new content';function myFunc(){return 'value of content: ' + content;}myFunc();"];
NSLog(@"result: %@", result);
// And calling myFunc() at this point is successful
result = [self.webView stringByEvaluatingJavaScriptFromString:@"myFunc();"];
NSLog(@"result: %@", result);
En resumen, yo esperaría que la variable global Javascript y la función que crearon . cuando cargo el html esté disponible para más tarde llamadas JavaScript Sorprendentemente, parece que no, y todos Javascript cosas hay que añadir más tarde, ¿es así
gracias por cualquier ayuda de antemano
.?. - --- actualización ----- Debo añadir que self.view es una WebView en este caso. Además, tengo t ried poner la etiqueta del script en la cabeza y el cuerpo del documento HTML, sin ningún cambio en el comportamiento.
Eso me sorprende también. Tengo que preguntar (sin relación con la pregunta), ¿por qué llamas myFunc() después de declararlo? – donkim
Ahh, eso fue solo para probar si pasaba algo. No debería estar allí. Sacarlo no hace nada. –