zoukankan      html  css  js  c++  java
  • iOS web view 与 js 交互

    移动应用中许多复杂的且经常改动的页面会使用H5进行代替native,这里就会使用到js和webview的交互

    iOS里面,UIWebView提供了方法stringByEvaluatingJavaScriptFromString:使js和webview互通

    这里我提供一种思路,仅供参考

    1.加载js函数

    var Test = {};
    Test.platform = {
    name: 'IOS'
    };
    // 返回App识别ID
    Test.getAppId = function(){
        return '[AppId]';
    };
    // 返回用户Id
    Test.getUserId = function(){
        return '[UserId]';
    };
    // 返回当前AppVersion
    Test.getAppVersion = function(){
        return '[AppVersion]';
    };
    Test.open = function(str){
        setTimeout(function(){
                   document.location = 'Test://open/'+str;
                   },50);
    };
    window.Test = Test;
    

    2.简单几个函数,加载前替换掉自己的value,

    for (NSString *key in dict) {
            NSString *placekey = [NSString stringWithFormat:@"[%@]", key];
            NSString *value = [dict[key] stringValue];
            if (! value || [value isEqual:[NSNull null]]) {
                jsString = [jsString stringByReplacingOccurrencesOfString:placekey withString:@"null"];
            }else{
                jsString = [jsString stringByReplacingOccurrencesOfString:placekey withString:value];
            }
        }
    

     3.加入webview的js里面:

       [webView stringByEvaluatingJavaScriptFromString:jsString];
    

     当js调用native的操作时候,可以使用Test.open(firstViewController?paramter=123)
    native的delegate将会调用:

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

    这里的request.url将会是:

    Test://open/firstViewController?paramter=123
    

     进入我们自己解析方法,对此url进行不同的解析和跳转

    NSString *requestString = [[request URL] absoluteString];
        NSArray *components = [requestString componentsSeparatedByString:@"://"];
    
        if (components[0] && [components count] > 1) {//如果协议抬头为Test或者为其他则走自定义流程
            NSString *content = components[1];
            NSArray *controller = [content componentsSeparatedByString:@"/"];
            if (controller.count > 1 && [controller[0] isEqual:@"open"]) {//打开特定的controller
                [self openController:controller[1]];
            }
        }
    
        return NO;
    
  • 相关阅读:
    wordpress通过$wpdb获取一个分类下所有的文章
    WordPress的摘要显示方式
    WordPress简洁的SEO标题、关键词和描述
    WordPress获取特色图像的链接地址
    WordPress的Bootstrap面包屑导航
    destoon 6.0 手机站支持在所有浏览器访问
    dede织梦5.7的安全防护设置
    WordPress主题制作:基础样式文件
    LInux常用到的命令(面试)
    1030 完美数列 (25分) PAT-B
  • 原文地址:https://www.cnblogs.com/OIMM/p/5938849.html
Copyright © 2011-2022 走看看