简体   繁体   English

在没有可见的uiwebview的情况下调用javascript Objective-C

[英]calling javascript objective-c without visible uiwebview

I want to call javascript functions from my objective-c. 我想从我的Objective-c调用javascript函数。 This for iphone. 这对于iPhone。 I understand how the call to the javascript function is done with this line 我了解此行如何完成对javascript函数的调用

NSString *returnValue = [webView stringByEvaluatingJavascriptFromString:method];

But I dont actually want a webview to be seen or used as part of the UI. 但我实际上并不希望将Webview视为UI或将其用作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. 在控制器的视图中添加webview以便运行javascript。 it won't be visible since it has zero height and width. 它的高度和宽度为零,因此不可见。

Your issue is not related to the size of the UIWebView . 您的问题与UIWebView的大小无关。 It is simply a timing issue. 这仅仅是一个时间问题。 The following code works as desired with a zero rect UIWebView instance. 以下代码可对零矩形UIWebView实例UIWebView Note the use of UIWebViewDelegate method webViewDidFinishLoad: . 注意,使用UIWebViewDelegate方法webViewDidFinishLoad: UIWebView is slow and it takes time for the view to load its content and be prepared to accept JavaScript commands. UIWebView速度很慢,视图需要花费一些时间来加载其内容并准备接受JavaScript命令。

@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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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