how to use javascript in uiwebview to get the clicked button id?

前端 未结 2 1179
时光说笑
时光说笑 2021-01-15 17:01

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

    appDelegate.mystring = [[NSMutableString string]init];
    NSString *b         


        
2条回答
  •  执念已碎
    2021-01-15 17:58

    Inside your html code use this snippet:

    
    
    
        
    
    
    
    
    
    
        link
        
    
    
    
    
    
    

    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;
    
    }
    

    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 :)

    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).

提交回复
热议问题