Chamar Javascript usando UIWebView
-
29-10-2019 - |
Pergunta
Estou tentando chamar um javascript em uma página html usando a função -
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()"];
}
Aqui está o javascript na página html -
<script>
function methodName()
{
// code to draw graph
}
No entanto, a função methodName()
não está sendo chamada, mas após window.onload= function () tudo está funcionando bem.
Estou tentando integrar RGraphs em meu aplicativo e Basic.html
é a página html na qual os javascripts são escritos.
Seria ótimo se alguém pudesse me ajudar com isso.
Solução
Simples: você tenta executar a função JS do Objective-C antes mesmo de a página ter sido carregada.
Implemente o método delegado de UIWebView webViewDidFinishLoad:
em seuUIViewController e nele você chama [graphView stringByEvaluatingJavaScriptFromString:@"methodName()"];
para garantir que a função seja chamada depois que a página tenha sido carregada.
Outras dicas
Para esclarecer um pouco mais.
.h - implemente o 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();"];
}
Você também pode atribuir o delegado do storyboard em vez de fazê-lo no código.