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

how to capture javascript button action in uiwebview

本文关键字:javascript 按钮 操作 uiwebview      更新时间:2023-09-26

我想知道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>

如何知道调用了哪个按钮。还需要窗口中的值。按钮点击操作上的位置

提前感谢

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

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

然后在您的Web视图代表中,实现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字符串以向前或向后翻页。