【问题标题】:how to capture javascript button action in uiwebview如何在 uiwebview 中捕获 javascript 按钮操作
【发布时间】:2013-08-09 00:44:03
【问题描述】:

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

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

我的当前页面是page2.html.On按钮动作,当前页面会后退和前进

我为两个按钮设置了名称和点击操作

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

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

提前致谢

【问题讨论】:

    标签: javascript iphone ios uiwebview


    【解决方案1】:

    在您的 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 字符串以向前翻页或相应地返回。

    【讨论】:

    • 我运行上面的代码,也改变了脚本,但显示后缀 =currentpage.html 现在显示“prevPage”或“nextPage”。你还有其他选择吗?
    • 不确定我是否理解 - 你能发布 urlString (request.URL.absoluteString) 的内容吗?
    • 这是(request.URL.absoluteString)的内容。我的当前页面是page2.html /Users/macuser/Library/Application Support/iPhone Simulator/5.0/Applications/A16998AD-105C-43E9 -A6F5-505FAFABBB68/htmlevents.app/page2.html.
    • 是在初始页面加载时吗?还是在您单击按钮之后? shouldStartLoadWithRequest 将在初始页面加载和在 javascript 代码中设置 window.location.href 时调用。您发布的 URL 看起来像初始页面加载。
    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 2017-07-22
    • 1970-01-01
    • 2015-06-05
    相关资源
    最近更新 更多