美文网首页
iOS JS交互

iOS JS交互

作者: 沉默的鱼sunny | 来源:发表于2017-11-24 16:41 被阅读0次

JS与UIWebView交互
一、
1.JS代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script>
            function showAlert(stringS){
                alert(stringS);
            }
            function testOne(){
                printFunction("https://www.baidu.com/")
            }
            function printFunction(urlString){
                var iFrame;
                iFrame = document.createElement("iframe");
                iFrame.setAttribute("src", messageData["type"] + messageData["moneyS"] + messageData["idS"]);
                iFrame.setAttribute("style", "display:none;");
                iFrame.setAttribute("height", "0px");
                iFrame.setAttribute("width", "0px");
                iFrame.setAttribute("frameborder", "0");
                document.body.appendChild(iFrame);
                // 发起请求后这个 iFrame 就没用了,所以把它从 dom 上移除掉
                iFrame.parentNode.removeChild(iFrame);
                iFrame = null;
            }
        </script>
    </head>
    <body>
        <button type="button" onclick="testOne()">按钮</button>
    </body>
</html>

OC代码

#pragma mark 网页监听
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{  
    NSString *requestString = request.URL.absoluteString.stringByRemovingPercentEncoding;
    //调用JS方法
    NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"这里是JS中alert弹出的message"];
    [_webView stringByEvaluatingJavaScriptFromString:jsStr];
    return YES;
}

二、
使用JavaScriptCore.framework,在target-->Build Phases-->Link Binary With Libraies添加框架。然后引入头文件。

#import <JavaScriptCore/JavaScriptCore.h>

声明

@property (nonatomic,weak) JSContext * context;

JS代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script>
            function showAlert(stringS){
                alert(stringS);
            }
            function one(){
              testOne();
              }
             function two(){
              testTwo('hello','hello',hello);
             }
        </script>
    </head>
    <body>
        <button type="button"  onclick="one()">按钮(无参)</button>
        <button type="button"  onclick="two()">按钮(传参)</button>
    </body>
</html>

OC代码

//当网页视图结束加载一个请求之后,得到通知。
-(void)webViewDidFinishLoad:(UIWebView*)webView
{
    //获取js的运行环境
    _context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        //html调用无参数OC
        _context[@"test1"] = ^(){

    };
    //html调用OC(传参数过来)
    //
    _context[@"testOne"] = ^(){
        NSArray * args = [JSContext currentArguments];//传过来的参数
        [self test:[NSString stringWithFormat:@"showAlert('success')"]];
    };
    //
    _context[@"testTwo"] = ^(){
        NSArray * args = [JSContext currentArguments];//传过来的参数
        [self test:[NSString stringWithFormat:@"showAlert('success')"]];
    };
}
- (void) test:(NSString *) result {
   JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    [context evaluateScript:result];
}

JS与WKWebView交互
JS调用WKWebView,JS如下代码

window.webkit.messageHandlers.方法名.postMessage(数据)

OC代码

WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
config.preferences = [[WKPreferences alloc] init];
   
 config.userContentController = [[WKUserContentController alloc] init];
    
 config.processPool = [[WKProcessPool alloc] init];
 WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
 webView.navigationDelegate = self;
 webView.UIDelegate = self;
 [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]];
 [self.view addSubview:webView];
 self.webView = webView;

添加注入js方法, oc与js端对应实现

[config.userContentController addScriptMessageHandler:self name:@"方法名"];
//WKScriptMessageHandler协议方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    //message.name 为 方法名 的名称
    if ([message.name isEqualToString:@"方法名"]) {
         NSLog(@"share = %@", message.body);
    }
}

处理拨打电话以及Url跳转等等

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    if ([scheme isEqualToString:@"tel"]) {
        NSString *resourceSpecifier = [URL resourceSpecifier];
        NSString *callPhone = [NSString stringWithFormat:@"telprompt://%@", resourceSpecifier];
        /// 防止iOS 10及其之后,拨打电话系统弹出框延迟出现
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:callPhone]];
        });
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

相关文章

网友评论

      本文标题:iOS JS交互

      本文链接:https://www.haomeiwen.com/subject/qijfbxtx.html