timpone
timpone

Reputation: 19979

UIWebView stringByEvaluatingJavaScriptFromString isn't calling javascript function

I have the following in a controller and don't understand why it is not calling the function in the page (it doesn't do anytihng). Any help is appreciated - first time using this:

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *fullURL = @"http://local.com/js-more.html";  // this does laod
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [arcWebView loadRequest:requestObj];

    NSString * param  = @"foo";   
    NSString * jsCallBack = [NSString stringWithFormat:@"myFunc('%@')",param];
    [arcWebView stringByEvaluatingJavaScriptFromString:jsCallBack];

and in the web page I have:

<script>

function myFunc(this_str){![enter image description here][1]
  alert('here is val: ' + this_str);
}
myFunc('here is in string');
</script>

and this gets alerted correctly in a browser or in an embedded UIWebView.

thx in advance

edit 1

enter image description here

Upvotes: 0

Views: 5272

Answers (1)

Bergasms
Bergasms

Reputation: 2203

I'd put the javascript inside the webviewdidfinishload delegate method. As the problem may be that your webpage is not loaded yet, even so you have called load request.

set the webviews delegate, put the code there, and it should work.

EG

- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *fullURL = @"http://local.com/js-more.html";  // this does laod
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [arcWebView setDelegate:self];
    [arcWebView loadRequest:requestObj];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSString * param  = @"foo";   
    NSString * jsCallBack = [NSString stringWithFormat:@"myFunc('%@')",param];
    [webView stringByEvaluatingJavaScriptFromString:jsCallBack];
}

Upvotes: 1

Related Questions