javascript - 如何在 uiwebview 中捕获 javascript 按钮操作

标签 javascript iphone ios uiwebview

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

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

我的当前页面是page2.html。在按钮操作上,当前页面将后退和前进

我为两个按钮都设置了名称和点击 Action

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

如何知道调用了哪个按钮。 还想要 window.location 中按钮单击操作的值

提前致谢

最佳答案

在你的 nextPage 和 prevPage javascript 方法中,创建一个你可以在你的 web View 委托(delegate)中解析的自定义 url:

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

然后在您的 Web View 委托(delegate)中,实现 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 字符串以向前翻页或相应地返回。

关于javascript - 如何在 uiwebview 中捕获 javascript 按钮操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18126459/

相关文章:

javascript - 色调/饱和度/最亮范围 slider 的功能

ios - RxSwift 教程示例 : Attribute can only be applied to types, 不是声明

ios - 从 APNS 消息中获取数据

ios - 在 Objective-C 中使用 SCRecorder 以修改后的播放速度保存视频

ios - 自定义 UITableViewCell,单元格中的按钮不起作用

javascript - SweetAlert 使用@Html.ActionLink 确认提示

javascript - 从html中获取内容

javascript - 关于自动版本化静态内容的问题

iphone - 撤消 UITextView 中的输入

javascript - 将 UIWebView 中的所有图像调整到一定宽度以上