Question

J'essaie d'appeler un javascript dans une page HTML en utilisant la fonction -

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()"];
}

Voici le javascript sur la page HTML -

<script>
    function methodName()
      {
         // code to draw graph
      }

Cependant, la fonction methodName() ne s'appelle pas mais après fenêtre.onload = function () tout fonctionne bien.

J'essaye d'intégrer Rgraphs dans ma demande et Basic.html est la page HTML dans laquelle les javascripts sont écrits.

Ce serait formidable si quelqu'un pouvait m'aider avec ça.

Était-ce utile?

La solution

Simple: vous essayez d'exécuter la fonction JS à partir de Objective-C avant même que la page soit chargée.

Mettre en œuvre le Méthode déléguée d'UiWebview webViewDidFinishLoad: Dans votre uiViewController et là-bas, vous appelez [graphView stringByEvaluatingJavaScriptFromString:@"methodName()"]; Pour s'assurer que la fonction est appelée après La page a été chargée.

Autres conseils

Pour clarifier un peu plus.

.h - Implémentez le 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();"];
}

Vous pouvez également attribuer le délégué de Storyboard au lieu de le faire dans le code.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top