pallavi_ios
pallavi_ios

Reputation: 117

how to capture javascript button action in uiwebview

I want to know which button is called of javascript in uiwebview, My script is

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

My current page is page2.html.On button action, current page will move backword and forward

I set name and onclick action to both buttons

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

how to know which button is called. also want the value inside window.location on button click action

Thanks in advance

Upvotes: 1

Views: 3354

Answers (1)

Jeff Loughlin
Jeff Loughlin

Reputation: 4174

In your nextPage and prevPage javascript methods, create a custom url that you can parse inside your web view delegate:

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

Then in your Web View delegate, implement 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;            
}

Of course that's just a simple example - in real code you'll want to replace @"Page1.html" and @"Page3.html" with code to keep track of the current page and build your url string to page forward or back accordingly.

Upvotes: 1

Related Questions