iOS and JS interaction

h5 code

        <meta charset='utf-8'/>
            function showAlert(String){
            function onClickOC(String){
            function clickCallBack(result){
                document.getElementById("result").innerHTML="Click results:"+result;
        <button type="button" onclick="onClickOC('html')">click me</button>
        <a href="tt://showmsg">showmsg</a>
        <p id="result">Click results:</p>

Intercept URL

For UIWebView and WKWebView, for h5 tags with hyperlinks, such as the 'a' tag in the h5 code above.

web tune OC

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    NSString *requestStr = request.URL.absoluteString;
    if ([requestStr isEqualToString:@"tt://showmsg"]) {
        NSLog(@"show OC msg");
        //OC calls JS to return OC processing result to web page
        [webView stringByEvaluatingJavaScriptFromString:@"clickCallBack('Click Finish')"];
        return NO;
    return YES;


Method 1: use block

-(void)webViewDidFinishLoad:(UIWebView *)webView
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
     context[@"onClickOC"] = ^(NSString *string) {
     NSLog(@"onClickOC--%@", string);

Method 2:

  • The new class inherits from NSObject (such as AppJSObject).  
  • The. h file declares a proxy and follows JSExport. The methods in the proxy are consistent with the method names defined by js.  
  • The corresponding method in < 2 > agent is implemented in. m file, which can handle events or notify agent within the method.
  • The AppJSObject instance object class is injected into JS in the agent that UIWebView completes loading. Then the calling method in JS will be invoked to the corresponding method in the native AppJSObject instance object.

#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>

@protocol APPJSObjectDelegate <JSExport>

-(void)onClickOC:(NSString *)name;


@interface APPJSObject : NSObject<APPJSObjectDelegate>

@property (nonatomic, weak) id<APPJSObjectDelegate> delegate;

#import "APPJSObject.h"

@implementation APPJSObject

-(void)onClickOC:(NSString *)name
    [self.delegate onClickOC:name];
-(void)webViewDidFinishLoad:(UIWebView *)webView
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    APPJSObject *obj = [[APPJSObject alloc] init];
    obj.delegate = self;
    context[@"app"] = obj;

OC tune JS

JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//js string is the JavaSCript function to call
NSString *js = [NSString stringWithFormat:@"clickCallBack('Click Finish')"];
[context evaluateScript:js];

Keywords: Javascript

Added by obscurr on Sat, 04 Jan 2020 10:45:25 +0200