UIWebView 中的 Javascript 回调到 C/Objective-C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2873899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:17:32  来源:igfitidea点击:

Javascript in UIWebView callback to C/Objective-C

javascriptobjective-cioscocoa-touchuiwebview

提问by LK.

Is there a way to get a callback to objective-c when a certain event has been detected in a UIWebView? Can Javascript send a callback to Objective-C?

当在 UIWebView 中检测到某个事件时,有没有办法回调到objective-c?Javascript 可以向 Objective-C 发送回调吗?

采纳答案by bpapa

Update - don't use UIWebView anymore. Use WKWebView, or better yet (if it fits your needs and you're building for iOS 9), a Safari View Controller.

更新 - 不再使用 UIWebView。使用 WKWebView,或者更好的(如果它满足您的需求并且您正在为 iOS 9 构建),一个 Safari 视图控制器。

But if you must use UIWebView, in your UIWebView delegate, provide an implementation for webView:shouldStartLoadWithRequest:navigationType:

但是如果你必须使用 UIWebView,在你的 UIWebView 委托中,提供webView:shouldStartLoadWithRequest:navigationType 的实现:

In your HTML or Javascript files, add functions that send URLs to a custom scheme (for readability purposes, the custom scheme isn't required). All the URLs sent will be passed to your Objective-C method implementation, and then you can do what you'd like.

在您的 HTML 或 Javascript 文件中,添加将 URL 发送到自定义方案的函数(出于可读性目的,不需要自定义方案)。所有发送的 URL 都会传递给你的 Objective-C 方法实现,然后你就可以做你想做的了。

回答by geon

Just to illustrate the solution by "bpapa" with actual code:

只是为了用实际代码说明“bpapa”的解决方案:

WARNING: untested code

警告:未经测试的代码

Implement this method in the UIWebView's delegate...

在 UIWebView 的委托中实现这个方法...

-(BOOL) webView:(UIWebView *)inWeb shouldStartLoadWithRequest:(NSURLRequest *)inRequest navigationType:(UIWebViewNavigationType)inType {
    if ( [[[inRequest URL] scheme] isEqualToString:@"callback"] ) {

        // Do something interesting...

        return NO;
    }

    return YES;
}

...then put a link in the webwieb like this:

...然后在 webwieb 中放置一个链接,如下所示:

<a href="callback:whatever">Click me</a>

And it should activate your callback-code. Obviously, you could trigger it with a javascript instead of a plain link.

它应该激活您的回调代码。显然,您可以使用 javascript 而不是普通链接来触发它。