使用UIWebView调用Javascript

lea*_*010 36 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()"];
}
Run Code Online (Sandbox Code Playgroud)

这是html页面上的javascript -

<script>
    function methodName()
      {
         // code to draw graph
      }
Run Code Online (Sandbox Code Playgroud)

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

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

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

Bjö*_*ser 68

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

在UIViewController中实现UIWebView的委托方法 webViewDidFinishLoad:,并在那里调用[graphView stringByEvaluatingJavaScriptFromString:@"methodName()"];以确保在页面加载调用该函数.

  • 这是一个非常有效的问题,根本不是一个愚蠢的问题..谢谢.我忘了设置代理..现在代码工作了...... (7认同)

Kal*_*ade 10

澄清一点点.

.h - 实现UIWebViewDelegate

@interface YourViewController : UIViewController <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@end
Run Code Online (Sandbox Code Playgroud)

.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();"];
}
Run Code Online (Sandbox Code Playgroud)

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