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.
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.
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