从UIWebview调用本地函数 [英] Local function call from UIWebview

查看:54
本文介绍了从UIWebview调用本地函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个uiwebview,我已经准备好将htmlstring格式的数据加载到webview中.

Hi i have an uiwebview, I have prepare the htmlstring format of data to load in webview.

我正在使用此行在uiwebview中加载htmlstring.

I am using this line to load htmlstring in uiwebview.

     [webView loadHTMLString:htmlstring baseURL:[NSURL URLWithString:[NSString stringWithFormat:@"file:/%@//",imagePath]]];

在html格式的字符串中,我们有一个图像按钮.当我单击图像按钮时,我想在ViewController.m文件中调用一个本地函数.

In the html formated string we have an one image button.When i click the image button i want to call one local function in ViewController.m file.

有可能吗?请帮助我.

我正在使用

<input type=""image"" onclick=""func()"" src=""icon_blog.png"" name=""image"" width=""30"" height=""30"">

  <script language=""javascript""> function func(){alert(""hee"");}

但警报未在iphone中显示.有人帮我吗?在此先感谢....

But alert not shown in iphone . Any one help me ? Thanks in advance.......

推荐答案

没有直接方法可以从UIWebView中加载的页面内调用Objective-c代码.

There is no straightforward way to call objective-c code from within page loaded in UIWebView.

唯一的方法是在UIWebView的委托(– webView:shouldStartLoadWithRequest:navigationType:)中拦截虚拟页面的加载.在那里您可以根据request.URL做出决定.

The only way is to intercept loading of dummy-pages in UIWebView's delegate (– webView:shouldStartLoadWithRequest:navigationType:). There you can make decisions based on request.URL.

- (BOOL)webView:(UIWebView*)_webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSArray *components = [[[request URL] absoluteString] componentsSeparatedByString:@":"];
    if ([components count] > 1 && [[components objectAtIndex:0] isEqualToString:@"objc"]) {
        if ([[components objectAtIndex:1] isEqualToString:@"someFunctionality"]) {
            // Do something
        }
        return NO;
    }
    return YES;
}

您可以通过单击链接,提交表单或通过设置如下窗口位置来从JavaScript触发这些请求:window.location = "objc:someFunctionality";.

You can trigger those requests by clicking a link, submitting a FORM, or from JavaScript by setting the window's location like this: window.location = "objc:someFunctionality";.

这篇关于从UIWebview调用本地函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆