iOS

js 与原生交互

2018-08-06  本文已影响0人  飞鱼ll

js

    function clickBtn(){
            var browser = {
                versions: function () {
                    var u = navigator.userAgent, app = navigator.appVersion;
                    return { //移动终端浏览器版本信息
                        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                        android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器
                        iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
                        iPad: u.indexOf('iPad') > -1, //是否iPad
                    };
                }(),
            };
            if (browser.versions.iPhone || browser.versions.iPad || browser.versions.ios) {
                // window.webkit.messageHandlers.test.postMessage(); // wkwebview
                test(); // uiwebview
            }

            if (browser.versions.android) {
                window.android.test(); // android
            }
        }
    

ios
uiwebview

#import <JavaScriptCore/JavaScriptCore.h>

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [self test];
}

- (void)test {
    
    //创建JSContext对象
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    //注册test方法
    context[@"test"] = ^() {
        dispatch_async(dispatch_get_main_queue(), ^{
           // 执行UI更新操作
        });
    };
}

wkwebview

#import <WebKit/WebKit.h>
<WKUIDelegate, WKScriptMessageHandler, WKNavigationDelegate>

WKUserContentController *userContentController = [[WKUserContentController alloc] init];
[userContentController addScriptMessageHandler:self name:@"test"];
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
config.userContentController = userContentController;
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];

// 从web界面中接收到一个脚本时调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"test"]) {
        // 执行操作
    }
}
上一篇下一篇

猜你喜欢

热点阅读