如何在 uiwebview 中使用 javascript 来获取点击的按钮 id?

how to use javascript in uiwebview to get the clicked button id?(如何在 uiwebview 中使用 javascript 来获取点击的按钮 id?)

本文介绍了如何在 uiwebview 中使用 javascript 来获取点击的按钮 id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这次我想知道如何确定在 UIWebView 中点击了哪个按钮.....

This Time i want to know how to determine which button is click in UIWebView.....

    appDelegate.mystring = [[NSMutableString string]init];
    NSString *buttonstring=@"<label><input type="submit" name="button" id="1" value="Delete" /></label>";

    for (int i=0; i<appDelegate.lyricsData.count; i++) {
    NSString *b= @"<br>";
    NSString *st1=[[appDelegate.lyricsData objectAtIndex:i] objectForKey:@"user_name"];
    appDelegate.mystring=[appDelegate.mystring stringByAppendingString:st1];
    appDelegate.mystring=[appDelegate.mystring stringByAppendingString:b];
    NSString *st2=[[appDelegate.lyricsData objectAtIndex:i] objectForKey:@"added_date"];
    appDelegate.mystring=[appDelegate.mystring stringByAppendingString:st2];
    appDelegate.mystring=[appDelegate.mystring stringByAppendingString:b];
    NSString *st3=[[appDelegate.lyricsData objectAtIndex:i] objectForKey:@"verse"];

    appDelegate.mystring=[appDelegate.mystring stringByAppendingString:st3];
    appDelegate.mystring=[appDelegate.mystring stringByAppendingString:buttonstring];
    appDelegate.mystring=[appDelegate.mystring stringByAppendingString:b];
    appDelegate.mystring=[appDelegate.mystring stringByAppendingString:b];



    btn_back1_en.tag = i;
    NSLog(@"%d",btn_back1_en.tag);
    [btn_back1_en addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [buttonArray insertObject:btn_back1_en atIndex:i];
    [btn_back1_en release];     



    }
    NSLog(@"My string %@",appDelegate.mystring);

    UIWebView *mywebview = [[UIWebView alloc] initWithFrame:CGRectMake(0,70, 320, 240)];
    mywebview.backgroundColor=[UIColor clearColor];
    mywebview.opaque=NO;
    mywebview.dataDetectorTypes= UIDataDetectorTypeNone;



//  working
    NSString *htmlTempString = [NSString stringWithFormat:@"<html><head><meta name="viewport" content="width=200; initial-scale=1.0; maximum-scale=0; user-scalable=0;" />  </head>         <style> *{padding:0px;margin:0px;}.wrap{width:320px;background:#000000;color:#FFFFFF;font-family:'Myriad Pro',Arial, Helvetica, sans-serif; font-size:12px;}.head{  padding:15px 20px;background:url(images/bg.png) repeat-x bottom #383838;display:block; border:1px } .head-left{ float:left; width:54px;}.head-right{float:left; width:224px; clear:right; padding:0px 0px 8px 0px;} h1{ padding:0px;  font-size:16px; color:#fff;}  h2{ padding:0px; font-size:14px; color:#3a89d3;}small{ font-size:11px; color:#77c900; padding:0px;font-weight:normal;}  b{ padding:0px;font-size:16px; color:#fff; }.comments{ background:url(images/bot-line.png) no-repeat bottom left; padding:10px 0px;}.comments h1{ padding:0px;font-size:16px; color:#fff; display:inline}.comments h2{ padding:0px;font-size:14px; color:#3a89d3; display:inline; margin:0px;}.comments small{ font-size:11px; color:#77c900; padding:0px; margin:0px 0px 0px 5px; font-weight:normal; display:inline;} .comments b{ padding:0px; margin:0px 0px 5px 5px; font-size:16px; color:#fff; display:inline}   .status{padding:15px 20px;background:url(images/bg.png) repeat-x bottom #383838;display:block; margin:4px 0px; }    </style>    <body>  <div class="wrap">    <div class="head">    <div class="head-left"><img src="%@" width="54" height="54" /></div>    <div class="head-right">  <h1>%@</h1> <h2>%@</h2> <small>on %@</small>    </div>  <br clear="all" />    </div>  <div class="status"><b>%@</b><div class="comments"><h2>%@   </h2></div><br clear="all" /> </div></div>    </body></html>",    
                                appDelegate.profilepic,appDelegate.textfield,appDelegate.username,appDelegate.added_date,appDelegate.mytextview,appDelegate.mystring];




    [mywebview loadHTMLString:htmlTempString baseURL:nil];
    mywebview.delegate=self;

///按键代码

- (IBAction)buttonClick:(id)sender{
    NSLog(@"button %@",[sender tag]);
}

推荐答案

在您的 html 代码中使用以下代码段:

Inside your html code use this snippet:

<html>
<head>

    <script>

        function iOSNativeBridge(){

            this.sendRawMessageToiOS = function(message){
//              alert(message);
                console.log("Message string to iOS: [" + message+ "]");
                var iframe = document.createElement("IFRAME");
                iframe.setAttribute("src", "jscall://" + message);
                document.documentElement.appendChild(iframe);
                iframe.parentNode.removeChild(iframe);
                iframe = null;
            };

        }

        bridge = new iOSNativeBridge();


    </script>


</head>

<body>

    <a href="javascript:bridge.sendRawMessageToiOS('your message');">link</a>
    <input type="button" value="button val" name="button" id="1" onClick="javascript:bridge.sendRawMessageToiOS('your message');">

</body>


</html>

在原生端,在 uiwebview 的委托方法中:

on native side, in uiwebview's delegate method:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    NSString *jsCallPrefix = @"jscall://";
    NSString *fullURLRequested = request.URL.absoluteString;

    BOOL isJavaScriptCall = ([fullURLRequested hasPrefix:jsCallPrefix]);

    if (isJavaScriptCall) {
        NSString *messageConveyed = [fullURLRequested substringFromIndex:jsCallPrefix.length];
        NSLog(@"Your message was: %@", messageConveyed);
        return NO;
    }

    return YES;

}

关于网页端的代码 - 我不会无缘无故地处理这个动态创建的 iframe.乍一看,只需更改 webview 页面上的位置(调用 document.location.href = "jscall://message")似乎就足够了.最糟糕的是,这实际上似乎工作得很好.不幸的是,如果你走这条捷径,JS 定时器就会大打折扣.所以听我的建议 - 使用这个看起来很奇怪但工作没有任何副作用的sendRawMessageToiOS":)

With regards to the code on web side - I don't juggle with this dynamically created iframe without a reason. At first glance, it would seem sufficient just to change the location on webview's page (call document.location.href = "jscall://message"). The worst thing is, that is actually seems to work great. Unfortunately, if you take this shortcut, JS timers are messed up greatly. So take my advice - use this little, weird-looking, but working without any side-effects "sendRawMessageToiOS" as is :)

对上述代码中发生的事情进行更深入的描述:在网络代码中,每当我想将一些数据推送到我的应用程序的本机端时,我都会调用 sendRawMessageToiOS(dataInStringToSend).它创建一个 iframe,将其添加到 DOM 树并将其位置设置为"jscall://" + dataInStringToSend然后,正如预期的那样,会询问 uiwebview 的代表,我是否愿意启动从给定地址下载内容的请求.我检查它是否是实际地址(然后返回 YES)或者只是这个带有特殊jscall://"前缀的伪装.如果是这个特殊的调用,我会读取它传递的数据,然后响应 NO(因为 webview 不应该尝试启动任何真正的请求).

Little more in-depth description of what's going on in the above code: In the web-code, whenever I want to push some data to the native-side of my app, I call sendRawMessageToiOS(dataInStringToSend). It creates an iframe, adds it to the DOM tree and sets it's location to be "jscall://" + dataInStringToSend Then, as expected, the uiwebview's delegate is asked, whether or not I'm willing to start the request to download a content from a given address. I check if it's actual address (and return YES then) or only this masquerade with special "jscall://" prefix. If it is this special call, I read data that's conveyed with it, and respond NO (because webview should not try to start any real request).

这篇关于如何在 uiwebview 中使用 javascript 来获取点击的按钮 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 uiwebview 中使用 javascript 来获取点击的按钮 id?

基础教程推荐