简体   繁体   中英

calling javascript objective-c without visible uiwebview

I want to call javascript functions from my objective-c. This for iphone. I understand how the call to the javascript function is done with this line

NSString *returnValue = [webView stringByEvaluatingJavascriptFromString:method];

But I dont actually want a webview to be seen or used as part of the UI. So can I just create an instance of it right before calling the method above in some way.

I have tried:

UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectZero];
[webView loadRequest:[NSUrLRequest requestWithUrl:url]];

but nothing seems to happen. So is there a method similar to the above that I am meant to use.

add the webview in your controller's view in order to run the javascript. it won't be visible since it has zero height and width.

Your issue is not related to the size of the UIWebView . It is simply a timing issue. The following code works as desired with a zero rect UIWebView instance. Note the use of UIWebViewDelegate method webViewDidFinishLoad: . UIWebView is slow and it takes time for the view to load its content and be prepared to accept JavaScript commands.

@interface NGViewController () <UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *hiddenWebView;
@end

@implementation NGViewController

@synthesize hiddenWebView = _hiddenWebView;

- (void)viewWillLayoutSubviews
{
  [super viewWillLayoutSubviews];

  if (!self.hiddenWebView.superview)
  {
    [self.view addSubview:self.hiddenWebView];
  }
}

- (UIWebView *)hiddenWebView
{
  if (!_hiddenWebView) {
    _hiddenWebView = [UIWebView.alloc initWithFrame:CGRectZero];
    _hiddenWebView.delegate = self;
    [_hiddenWebView loadHTMLString:@"<html><head><script>window.james = 'My name';</script></head><body><h1>Hidden Web View by James</h1></body></html>" baseURL:nil];
  }
  return _hiddenWebView;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
  NSString *documentBodyString = [self.hiddenWebView stringByEvaluatingJavaScriptFromString:@"window.james;"];
  NSLog(@"The body's inner HTML is: %@", documentBodyString);
}

@end

The output of which is:

2013-07-09 03:13:29.347 WebViewTest[14261:c07] The body's inner HTML is: My name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM