ios - 将数据传入和传出嵌入式 UIWebView

标签 ios uiwebview

我的 View Controller 中嵌入了一个 UIWebView,如下所示:

enter image description here

我的 WebView ( _graphTotal ) 有一个导出,我可以成功加载 test.html 的内容在其中使用:

[_graphTotal loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

我现在正尝试将数据传递到 WebView ,但没有成功。我添加了 <UIWebViewDelegate>这就是我正在尝试的:

NSString *userName = [_graphTotal stringByEvaluatingJavaScriptFromString:@"testFunction()"];
NSLog(@"Web response: %@",userName);

这里是test.html的内容在我的项目中:

<html>
  <head></head>
  <body>
    Testing...
      <script type="text/javascript">
        function testFunction() {
          alert("made it!");
          return "hi!";
        }
        </script>
  </body>
</html>

我可以在我的 webView 中看到“Testing...”,但我没有看到警报,也没有看到返回的“hi!”字符串。

知道我做错了什么吗?

最佳答案

好吧,问题是您试图在 webview 有机会加载页面之前评估您的 javascript。先采纳<UIWebViewDelegate>协议(protocol)进入你的 View Controller :

@interface ViewController : UIViewController <UIWebViewDelegate>

然后将您的 webview 的委托(delegate)连接到您的 View Controller ,发出请求并最终实现 delegate methods .这是在 webview 完成加载时通知您的:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [self.graphTotal loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSString *userName = [self.graphTotal stringByEvaluatingJavaScriptFromString:@"testFunction()"];
    NSLog(@"Web response: %@",userName);
}

PS:当您以这种方式评估 javascript 时,您必须注意的限制之一是您的脚本必须在 10 秒内执行。因此,例如,如果您等待超过 10 秒才关闭警报,您将收到错误消息(等待 10 秒后无法返回)。查找有关限制的更多信息 in the docs .

关于ios - 将数据传入和传出嵌入式 UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17117713/

相关文章:

ios - Swift 2 - CoreData - NSManagedObjectContext 无法使用类型为 'save' 的参数列表调用 '(inout NSError?)'

ios - 在 (BOOL)webView : How to open a URL clicked in UIWebView that opens a Modal UIWebView 内

ios - 在 ios 上使用 firebase 分析时出现观众错误

ios - 在 Swift 中使用 NSStream 连接到 Redis 服务器

ios - 在 iOS 中加载多个图像时,使用 send_data 加载的图像半损坏

ios - 使用 PFLogInViewController 创建 PFUser 后,Parse.com iOS 用户电子邮件打开可读

ios - UIWebView 以更有效的方式减少加载时间

ios - SWIFTUI 在 TabView 中隐藏当前 View 的 navigationBarBackButton

ios - UIWebView 中的后台音频播放

xcode - HTML 标签未在 UIWebView 中呈现?