WebView/UIWebView中的javascript和object-c对象如何相互通信?
我发现 OSX/iOS 中的 WebView/UIWebView 使我们能够使用 html/css/javascript 构建精美的 UI 布局。我想知道UIWebView中的javascript如何调用UIWebView之外的object-c对象?
我在论坛里搜索了一下,发现了这个帖子: UIWebView 中的 Javascript 回调到 C/Objective-C 和此处的文档。
但这似乎是仅当视图加载/加载完成或类似情况时才会调用 Web 视图委托的唯一方法。 javascript有什么办法可以随时调用视图之外的对象吗?
I found WebView/UIWebView in OSX/iOS give us great ability to build fancy UI layout with html/css/javascript. I'd like to know how javascript in the UIWebView can call the object-c object outside the UIWebView?
I searched in the forum, and found this thread:
Javascript in UIWebView callback to C/Objective-C
and document here.
But it seems only way the web view delegate will be called only when the view load/load finish or something like that. Is there any way the javascript can call the object outside the view at any time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这里查看我的答案: UIWebview 中的 NSString
See my answer here: NSString in UIWebview
我发现在 UIWebView 中设置
window.location
似乎有副作用。特别是,它可以防止 DOM 的任何进一步 JS 操作,即使您的shouldStartLoadWithRequest:
返回 YES。有一个涉及轮询机制的控制台日志记录解决方案,所述解决方案here 可以扩展为允许调用任意 Objective-C 方法 - 但它可能会对性能产生影响。
如果您愿意不使用 javascript
alert()
函数,另一种解决方案是重写类别中 UIWebView 的runJavaScriptAlertPanelWithMessage:
方法。 此处用于更改警报对话框的外观,但也可用于根据消息内容调用任意 Objective-C 方法。但是,请注意,这是一个未记录的 API,因此不应在生产中使用(它可能会导致您的应用程序被拒绝)。I have found that setting
window.location
inside UIWebView seems to have side-effects. In particular, it prevents any further JS manipulation of the DOM, even if yourshouldStartLoadWithRequest:
returns YES.There is a solution for console logging involving a polling mechanism described here which could be extended to allow invocation of any arbitrary objective-c method - but it probably would have performance implications.
Another solution, if you are willing to do without the javascript
alert()
function is to override the UIWebView'srunJavaScriptAlertPanelWithMessage:
method in a Category. This is used here to change the look of the alert dialog, but could also be used to invoke any arbitrary objective-c method based on the contents of the message. However, be warned that this is an undocumented API and therefore shouldn't be used in production (it will likely get your app rejected).