将警报从UIWebView传递到iOS应用程序

pass alert from UIWebView to iOS app

本文关键字:iOS 应用程序 UIWebView      更新时间:2023-09-26

我已经创建了一个应用程序,它运行良好。我唯一需要的就是将警报从uiwebview传递到我的iOS应用程序。

我的uiwebview 上有这个警报

<div id="alerts" class="alerts">
<p class="alert-red">ok. come back again tomorrow, not now.</p>

我想将此警报转移到我的应用程序中,并使其成为uialertview

UIAlertView *errr = [[UIAlertView alloc]initWithTitle:@"nil" message:@"ok. come back again tomorrow, not now." delegate:self cancelButtonTitle:@"Ok, Got it" otherButtonTitles:nil, nil];
    [errr show];

知道如何达到这个结果吗?当此警报显示在uiwebview上时,我是否需要NSNotification来侦听?

我试过这种

NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"var targetDiv = document.getElementById('alerts').getElementsByClassName('alert-red')[0];"];
NSLog(@"%@",theTitle);

因此,我可以尝试从"红色警报"中检索该消息,但不起作用。

我是javascript和html 的新手

这是用于解决此问题的典型解决方法:

当你想显示此警报时,请在你的网页中运行以下javascript代码:

window.location = 'custom_action';

然后在objc中在控制器上实现shouldStartLoadWithRequest(并设置yourWebView.delegate = yourController

-(BOOL)webView:(UIWebView *)webView
       shouldStartLoadWithRequest:(NSURLRequest *)request
       navigationType:(UIWebViewNavigationType)navigationType {
  // detect when the webview switches to this custom url
  if([[[request URL] absoluteString] isEqualToString: @"custom_action"]) {
    UIAlertView *errr = [[UIAlertView alloc]initWithTitle:@"nil" message:@"ok. come back again tomorrow, not now." delegate:self cancelButtonTitle:@"Ok, Got it" otherButtonTitles:nil, nil];
    [errr show];
    // this prevents the webview from actually trying to load the custom url
    return NO;
  }
  // allow the url to load if its not your custom url
  return YES;
}