xcode uiwebview 中的 javascript 事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6869199/
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
javascript event Handler in uiwebview
提问by Royal Pinto
I am displaying one UIWebView in my iPhone application. In UIWebView I am displaying HTML page which has JavaScript also. I want to call method(of X Code) when one button is clicked in HTML page.
我在我的 iPhone 应用程序中显示一个 UIWebView。在 UIWebView 中,我正在显示也有 JavaScript 的 HTML 页面。我想在 HTML 页面中单击一个按钮时调用方法(X 代码)。
How can I do this. Thanks
我怎样才能做到这一点。谢谢
回答by cduhn
If I understand your question correctly, you want to call an Objective C method from a javascript onClick
event handler in your UIWebView
. The way to do that is to redirect the browser to a URL with a custom scheme in your javascript code like this:
如果我没有理解你的问题,你要调用从一个javascript的目标C方法onClick
事件处理程序在你的UIWebView
。这样做的方法是在您的 javascript 代码中使用自定义方案将浏览器重定向到 URL,如下所示:
function buttonClicked() {
window.location.href = "yourapp://buttonClicked";
}
Back in Objective C, declare that your view controller conforms to the UIWebViewDelegate
protocol,
回到 Objective C,声明你的视图控制器符合UIWebViewDelegate
协议,
@interface DTWebViewController : DTViewController <UIWebViewDelegate> {
...
set your controller as the web view's delegate,
将您的控制器设置为 Web 视图的委托,
- (void)viewDidLoad {
[super viewDidLoad];
self.webView.delegate = self;
}
and intercept the URL before it loads like this:
并在它加载之前拦截 URL,如下所示:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[request.URL scheme] isEqual:@"yourapp"]) {
if ([[request.URL host] isEqual:@"buttonClicked"]) {
[self callYourMethodHere];
}
return NO; // Tells the webView not to load the URL
}
else {
return YES; // Tells the webView to go ahead and load the URL
}
}
回答by noob
Swift Version
迅捷版
webView.delegate = self
extension ViewController: UIWebViewDelegate {
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.description == "yourappname://buttonClicked" {
// do your stuff here
return false
}
return true
}
}
Example HTML
示例 HTML
<a href="yourappname://buttonClicked">
<img src="http://someurl.com/table_desktop.jpg"/ width="100%">
</a>
If you want to know how to do it in wkWebView
, here is the link
如果你想知道怎么做wkWebView
,这里是链接