Calling Javascript using UIWebView

[亡魂溺海] 提交于 2019-11-26 07:38:10

问题


I am trying to call a javascript in a html page using the function -

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

Here is the javascript on the html page -

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

However, the function methodName() is not getting called but after window.onload = function () everything is working fine..

I am trying to integrate RGraphs into my application and Basic.html is the html page in which the javascripts are written.

It would be great if someone could help me out with this.


回答1:


Simple: You try to execute the JS function from Objective-C before the page even has been loaded.

Implement the UIWebView's delegate method webViewDidFinishLoad: in your UIViewController and in there you call [graphView stringByEvaluatingJavaScriptFromString:@"methodName()"]; to make sure the function gets called after the page has been loaded.




回答2:


To clarify a little bit more.

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

You could also assign the delegate from storyboard instead of doing it in the code.



来源:https://stackoverflow.com/questions/8886443/calling-javascript-using-uiwebview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!