如何在uiwebview中捕获javascript按钮动作

时间:2013-08-08 12:48:10

标签: javascript iphone ios uiwebview

我想知道在uiwebview中调用哪个javascript按钮, 我的脚本是

 function nextPage()
 {
   window.location = "page3.html";
 }
function prevPage()
 {
      window.location = "page1.html";
 }

我当前的页面是page2.html。在按钮操作中,当前页面将向后移动

我将名称和onclick动作设置为两个按钮

<button onclick="prevPage();" id="back"></button>
<div id="counter">Page 1 of 13</div>
 <button onclick="nextPage();" id="next"></button>
</div>

如何知道调用哪个按钮。 也希望window.location里面的值点击按钮点击动作

提前致谢

1 个答案:

答案 0 :(得分:1)

在您的nextPage和prevPage javascript方法中,创建一个可以在Web视图委托中解析的自定义URL:

function nextPage()
{
    window.location.href = "file://yourappname?nextPage";
}
function prevPage()
{
     window.location.href = "file://yourappname?prevPage";
}

然后在Web View委托中,实现shouldStartLoadWithRequest:

-(BOOL)webView:(UIWebView *)webView 
shouldStartLoadWithRequest:(NSURLRequest *)request 
 navigationType:(UIWebViewNavigationType)navigationType 
{
    NSString *urlString = request.URL.absoluteString;
    if (urlString hasSuffix:@"prevPage"])
    {
        NSURL *url = [NSURL urlWithString:@"Page1.html"];
        NSURLRequest *urlRequest = [NSUrlRequest requestWithURL:url];
        [webView loadRequest:urlRequest];
    }
    else if ([queryString hasSuffix:@"nextPage"])
    {
        NSURL *url = [NSURL urlWithString:@"Page3.html"];
        NSURLRequest *urlRequest = [NSUrlRequest requestWithURL:url];
        [webView loadRequest:urlRequest];
    }
    return YES;            
}

当然这只是一个简单的例子 - 在实际代码中,你需要用代码替换@“Page1.html”和@“Page3.html”以跟踪当前页面并构建你的url字符串以向前翻页或者相应地回来。