ios调用Html内JS alert 不能点击关闭为甚?

用ios上用webview加载了一个本地的HTML文件,代码如下

    //load test.html 到 webview

NSString *resourcePath = [[NSBundle mainBundle] resourcePath];

NSString *filePath =[resourcePath stringByAppendingPathComponent:@"test.html"];

NSString*htmlstring=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

[myWebView loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[ [NSBundle mainBundle] bundlePath]]];

test.html 内容如下

<!DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<a href="3dker://api/jsToNative?params=21321&callback=show">jsToNative</a><br>

<a href="3dker://api/nativeToJs?params=21321&callback=show">nativeToJs</a>

<h1>JS 调用 Native</h1>

<p>This is a paragraph.</p>

<button onclick="fn()">调用Native变色</button>

<button onclick="fn1()">去下一个webview页面</button>

<p></p>

<button onclick="fn2()">去下一个Native页面</button>

</body>

<script type="text/javascript">

var fn=function(){

window.location.href = "shining3dker://api/getData?params=bianse&callback=show";

}

var fn1=function(){

window.location.href = "shining3dker://goto/forward?url=3dker.cn&type=webview&param=321321321";

}

var fn2=function(){

window.location.href = "shining3dker://goto/forward?url=3dker.cn&type=native&param=12321321321";

}

</script>

<script>

var show = function(json){

alert(json);

}

</script>

</html>

然后我做了一个消息中心的监听,监听scheme的变化,在监听方法内我写到

//接受消息中心信息

-(void)get:(NSNotification *)notification{

NSDictionary *dic = notification.object;

//此处有个判断,就是说判断一下让testlabel变色而已

[testlabel setBackgroundColor:[UIColor blueColor]];

//webview调用js 的 show方法弹出alert

[myWebView stringByEvaluatingJavaScriptFromString:@"show(\"调用变色方法成功(native调用js alert)\");"];

}

问题是,Alert能正常弹出,但是不能点击ok让它关闭
我即便是输入
[myWebView stringByEvaluatingJavaScriptFromString:@"alert()"];
输出的alert也是不能点击的。
但是如果把JS alert的代码放在webViewDidFinishLoad内就是正常好用的。难道在消息中心处理完响应后不可以弹出js 的alert吗?我觉得很奇怪,求指教
如图图片描述

回答:

This question gave me the most insight to the problem...

Deadlock with GCD and webView

The gist is that the thread handling the JS from the stringByEvaluatingJavaScriptFromString: method and the thread handling the iOS alert view are probably blocking each other, making the "Close" button unresponsive.

My workaround is to defer the JS alert with a setTimeout, something like this...

NSString *jsMyAlert = @"setTimeout(function(){alert('FOOBAR');}, 1);";

[myWebView stringByEvaluatingJavaScriptFromString:jsMyAlert];
To avoid any risk of deadlock, it might be better to have the UIWebView trigger an UIAlertView rather than rely on UIWebView to handle the JS alert. The workaround above would be suitable for most debugging purposes though.

以上是 ios调用Html内JS alert 不能点击关闭为甚? 的全部内容, 来源链接: utcz.com/p/184031.html

回到顶部