0

I'm calling stringByEvaluatingJavaScriptFromString with a js function call ([self.webview stringByEvaluatingJavaScriptFromString:@"someMethod()"].

On the iphone it is returning an empty string but when I debug in safari using "Develop -> myphone -> index.html" the same call returns a correct result as expected.

I should also point out that the JS file with the method sits locally on the device as with the whole "website"

How can i check this ?

Avba
  • 14,822
  • 20
  • 92
  • 192

1 Answers1

0

First, you need to be sure that the webView has loaded properly, so do any code after it has notified you that it's done with the UIWebViewDelegate method. Then, you have to make sure that you are at the right URL for that JS method to work (you could be redirected to a mobile site (look for .m in the URL)). If you are, there's probably no helping it, so you will have to test any JS you'll use on the iPhone on the mobile website, by opening the same URL in your computer and looking around. Run this test:

#import "MyWebViewController.h"

@interface MyWebViewController() <UIWebViewDelegate>

// If you have a storyboard
@property (nonatomic, weak) IBOutlet UIWebView *webView;
// If you don't have a storyboard
// @property (nonatomic, strong) UIWebView *webView;

@end

@implementation MyWebViewController

- (void)viewDidLoad
{
//    If you don't have a storyboard
//    self.webView = [[UIWebView alloc] initWithFrame:self.view.frame];
//    [self.view addSubview:self.webView];
    self.webView.delegate = self;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"The URL of the site we are on is: %@", webView.request.URL.absoluteString);
    NSLog(@"Now, I'll evaluate the JS: %@", [webView stringByEvaluatingJavaScriptFromString:@"someMethod()"]);
}

@end
michaelsnowden
  • 6,031
  • 2
  • 38
  • 83
  • I'm loading locally held html and javascript using [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"htmldir"] - and the page is loading correctly according to the delegate methods – Avba Jul 07 '14 at 17:28
  • @AvnerBarr The delegate methods sort of lie because `webViewDidFinishLoad` is called multiple times. In order to get the last load, check this answer: http://stackoverflow.com/a/2796540/2770572 – michaelsnowden Jul 07 '14 at 18:20
  • its called once - I want to mention that the html and java script is local – Avba Jul 07 '14 at 18:24
  • also want to mention that I am calling the javascript way after the page has loaded – Avba Jul 07 '14 at 19:36
  • @AvnerBarr What is the JS, and what is the URL? – michaelsnowden Jul 08 '14 at 00:35