简体   繁体   中英

Calling Javascript function from native code (iOS)

这就是我的故事板的样子

This is my Story Board. I have used SWRevealViewController plugin for my side menu in cordova application. Added "Main View Controller" as class reference to the Last view controller(having item in nav-bar) .

On swiping from left to right on my cordova view will reveal Sidemenu. On click I'm saving selected row value in

 -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // menuItems is an array using which I'm populating the sidemenu
    NSString *  str = [menuItems objectAtIndex:indexPath.row];
}

I just want to pass this value to the javascript function.

Defined my javascript function in index.html

    <script >
    (function () {
     window.execute = function () {
     alert(" machi");
     var el = document.getElementById('search');
     var scope = angular.element(el).scope();
     scope.$apply(function() {
                  scope.execute();
                  });

     }
     })();
    </script>

    calling this function using
      NSString *jsCommand = [NSString stringWithFormat:@"execute()"];
    [self.webView stringByEvaluatingJavaScriptFromString:jsCommand];

Try to change your native code to:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // menuItems is an array using which I'm populating the sidemenu
    NSString *  str = [menuItems objectAtIndex:indexPath.row];
    NSString *jsCommand = [NSString stringWithFormat:@"execute('%@')", str];
    [self.webView stringByEvaluatingJavaScriptFromString:jsCommand];
}

And your javascript function declaration to:

 window.execute = function (str) {...}

You will find your passed value into str function parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM