Heim  >  Artikel  >  Web-Frontend  >  Erklären Sie im Detail, wie JS mit der App interagiert (Code im Anhang)

Erklären Sie im Detail, wie JS mit der App interagiert (Code im Anhang)

亚连
亚连Original
2018-05-18 10:13:542682Durchsuche

Das Folgende ist die Methode der Interaktion zwischen JS und App, die ich für Sie zusammengestellt habe. Interessierte Studenten können einen Blick darauf werfen.

1. Verbindung von Code auf H5

Wichtige Punkte: 1. Parameterübergabe des Objekttyps, 2. Die gleiche JS-Methode für die Interaktion mit der App, 3. Skriptmethode Es muss in den Kopf eingebettet werden.

<html>
    <head>
        <meta http-equiv="Content-Type"    content="text/html;charset=UTF-8">
            <script type="text/javascript">
                var share = JSON.stringify({"title":"Migi000",
                                          "desc":"简书",
                                           "shareUrl":"http://www.jianshu.com/p/f896d73c670a"
                                           });
            //IOS
            function startFunction(share){
               window.android.startFunction(share)//android
            }
                </script>
<script>
     // testFunction()
    </script>
    <divonClick="testFunction()">dffddjjjjlj;ljlhhnljkhljhkjf</div>
     <divid="app-root"></div>
    <script type="text/javascript"src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <script>
      var _hmt = _hmt || [];(function() {var hm= document.createElement("script");hm.src ="//hm.baidu.com/hm.js?f84dde8c08e5b9c97f9c39e2fcb4d658";var s =document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm, s);})();
    </script>
    <scripttype="text/javascript">
      function loadURL(url)
        {
            var iFrame;
            iFrame =document.createElement("iframe");
           iFrame.setAttribute("src", url);
            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;
        }
        function testFunction(share)
        {
           loadURL("testfunction://?title=分享的标题&content=分享的内容&url=链接地址&imagePath=图片地址");
        }
        var share =JSON.stringify({"title": "分享的标题","content":"分享的内容","url":"http://www.jianshu.com/p/f896d73c670a"});
        testFunction(share)    </script>
    </head>
    <body>
     <br/>
    <h1>Objective-C和JavaScript交互的那些事    </h1>
  <br/>
        <input  type="button" value="Share" onClick="startFunction(share)" >点击调用原生代码并传递参数</a>
</body>
</html>

2. Code-Andocken unter IOS

Hinweis: #importdcbd4dc34be872dd53e0bb4d60d07d16 muss in der .h-Datei platziert werden

#import"ViewController.h"
#import<JavaScriptCore/JavaScriptCore.h>
@interfaceViewController ()<UIWebViewDelegate>@property (nonatomic)UIWebView*webView;
@property(nonatomic)JSContext *jsContext;
@property(nonnull,strong) UIButton *btn;
@end
@implementationViewController
-(void)viewDidLoad{
    [super viewDidLoad];
    self.webView = [[UIWebViewalloc]initWithFrame:self.view.bounds];
    self.webView.delegate = self;
    [self.view addSubview:_webView];
    NSString *str = [[NSBundle mainBundle]pathForResource:@"migi" ofType:@"html"];
    [self.webView loadRequest:[NSURLRequestrequestWithURL:[NSURL fileURLWithPath:@"f"]]];
    // 在上面添加一个按钮,实现oc端控制h5实现弹alert方法框
    self.btn = [[UIButton alloc]initWithFrame:CGRectMake(100,400,100, 40)];
    self.btn.backgroundColor = [UIColorredColor];
    [self.btn addTarget:selfaction:@selector(showAlert) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.btn];
}
-(void)showAlert
{
    //要将script的alert()方法转化为string类型
    NSString *alertJs=@"alert(&#39;Hello Word&#39;)";
    [_jsContext evaluateScript:alertJs];
}
-(void)webViewDidFinishLoad:(UIWebView*)webView{
    _jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    _jsContext[@"startFunction"] =^(id obj){
////这里通过block回调从而获得h5传来的json数据
        /*block中捕获JSContexts
        我们知道block会默认强引用它所捕获的对象,如下代码所示,如果block中直接使用context也会造成循环引用,这使用我们最好采用[JSContext currentContext]来获取当前的JSContext:
         */
        [JSContext currentContext];
        NSData *data = [(NSString *)objdataUsingEncoding:NSUTF8StringEncoding ];
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:nil];
        NSLog(@"data   %@   ====== ShareUrl %@",obj,dict[@"shareUrl"]);
    };
    //
    _jsContext.exceptionHandler = ^(JSContext*context, JSValue *exceptionValue) {
        context.exception = exceptionValue;
        //比如把js中的方法名改掉,OC找不到相应方法,这里就会打印异常信息
        NSLog(@"异常信息:%@", exceptionValue);
};
_jsContext[@"testFunction"] =^(id obj){
            //这里通过block回调从而获得h5传来的json数据
            [JSContext currentContext];
            NSData *data = [(NSString *)objdataUsingEncoding:NSUTF8StringEncoding ];
            NSDictionary *dict = [NSJSONSerializationJSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//            NSLog(@" data   %@  ======  ShareUrl%@",obj,dict[@"shareUrl"]);
            UIAlertView *alertView = [[UIAlertViewalloc] initWithTitle:dict[@"title"]message:dict[@"content"]delegate:nilcancelButtonTitle:@"cancel"otherButtonTitles:nil,nil];
            [alertView show];
        };
}
-(BOOL)webView:(UIWebView *)webViewshouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL * url = [requestURL];
    //NSLog(@"scheme信息:%@", [urlscheme]);
    if ([[url scheme] isEqualToString:@"testfunction"])
    {
        NSArray *params =[url.querycomponentsSeparatedByString:@"&"];
        NSMutableDictionary *tempDic = [NSMutableDictionarydictionary];
        for (NSString *paramStrin params) {
            NSArray *dicArray = [paramStrcomponentsSeparatedByString:@"="];
            if (dicArray.count >1) {
                NSString *decodeValue =[dicArray[1]stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                [tempDic setObject:decodeValueforKey:dicArray[0]];
            }
        }
        UIAlertView *alertView = [[UIAlertViewalloc] initWithTitle:tempDic[@"title"]message:tempDic[@"content"]delegate:selfcancelButtonTitle:@"收到"otherButtonTitles:nil];
        [alertView show];
        NSLog(@"tempDic:%@",tempDic);
        return NO;
    }
    return true;   //为yes加载内容,否则不
}

3 Interaktion auf

mWebH5.addJavascriptInterface(new MyJavaScriptInterface(this), "android");
mWebH5.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        //返回值是true的时候控制去WebView打开,为false调用系统浏览器或第三方浏览器        view.loadUrl(url);        return true;
    }
});
@JavascriptInterface
 publicvoid startFunction(String json){
    if(SharedPrefs.getInstance().getUserAccessToken()==null){
    Gson gson=new Gson();
    finalShareLinkBean shareLinkBean =gson.fromJson(json, ShareLinkBean.class);
    LogUtils.i("test",json);
    mActivity.runOnUiThread(new Runnable() {
        @Override
        publicvoid run() {
            //跑相关逻辑
        }
    });
 }

Das Obige habe ich für Sie zusammengestellt, um mit JS und der App zu interagieren. Ich hoffe, dass es in Zukunft für alle hilfreich sein wird.

Verwandte Artikel:

Detaillierte Erläuterung der Verwendung von Js apply() (einschließlich Code)

Einfach und unkompliziert zum Verstehen, Selbststudium Javascript-Studiennotizen

Mehrere Lösungen zum automatischen Ausführen (Laden) von js auf der Seite, detaillierte Codeanalyse

Das obige ist der detaillierte Inhalt vonErklären Sie im Detail, wie JS mit der App interagiert (Code im Anhang). Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn