Llamar a Javascript usando UIWebView
-
29-10-2019 - |
Pregunta
Estoy intentando llamar a un javascript en una página html usando la función -
View did load function
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"BasicGraph.html"];
NSURL *urlStr = [NSURL fileURLWithPath:writablePath];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"BasicGraph" ofType:@"html"];
[fileManager copyItemAtPath:myPathInfo toPath:writablePath error:NULL];
[graphView loadRequest:[NSURLRequest requestWithURL:urlStr]];
}
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
[graphView stringByEvaluatingJavaScriptFromString:@"methodName()"];
}
Aquí está el javascript en la página html -
<script>
function methodName()
{
// code to draw graph
}
Sin embargo, no se llama a la función methodName()
pero después de window.onload= function () todo funciona bien ..
Estoy tratando de integrar RGraphs en mi aplicación y Basic.html
es la página html en la que están escritos los javascripts.
Sería genial si alguien pudiera ayudarme con esto.
Solución
Simple: intentas ejecutar la función JS desde Objective-C incluso antes de que se haya cargado la página.
Implemente el método de delegado de UIWebView webViewDidFinishLoad:
en suUIViewController y allí llama a [graphView stringByEvaluatingJavaScriptFromString:@"methodName()"];
para asegurarse de que la función se llame después de que se haya cargado la página.
Otros consejos
Para aclarar un poco más.
.h: implementar UIWebViewDelegate
@interface YourViewController : UIViewController <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
.m
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *path = @"http://www.google.com";
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]];
_webView.delegate = self; //Set the webviews delegate to this
}
- (void) webViewDidFinishLoad:(UIWebView *)webView
{
//Execute javascript method or pure javascript if needed
[_webView stringByEvaluatingJavaScriptFromString:@"methodName();"];
}
También puede asignar el delegado del guión gráfico en lugar de hacerlo en el código.