使用UIWebView调用Javascript

时间:2012-01-16 21:23:29

标签: javascript uiwebview ios5 rgraph

我正在尝试使用函数 -

在html页面中调用javascript
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()"];
}

这是html页面上的javascript -

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

然而,函数methodName()没有被调用但是在window.onload = function()之后一切正常......

我正在尝试将RGraphs集成到我的应用程序中,Basic.html是用于编写javascripts的html页面。

如果有人可以帮我解决这个问题会很棒。

2 个答案:

答案 0 :(得分:68)

简单:在页面加载之前,您尝试从Objective-C执行JS函数。

在你的UIViewController中实现UIWebView's delegate method webViewDidFinishLoad:,并在那里调用[graphView stringByEvaluatingJavaScriptFromString:@"methodName()"];以确保在页面加载后调用函数。< / p>

答案 1 :(得分:10)

澄清一点。

.h - 实现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();"];
}

您也可以从故事板中分配委托,而不是在代码中进行委托。