分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 前端开发

JS和webView的交互

发布时间:2023-09-06 01:46责任编辑:熊小新关键词:暂无标签

JSContext的交互方式最为简单快捷:

1.申明一个JSContext对象

    self.jsRunner = [[JSContext alloc] init];

2.在原生中定义申明一个JS函数方法(JS代码函数中可以使用)

    self.jsRunner[@"action1"] = ^(int value){

        printf("啦啦啦\n");

    };

    self.jsRunner[@"action2"] = ^(JSValue *value){

        NSLog(@"%@",value);

    };

3.通过执行JS代码的方式执行自己定义的函数(热更新通过加载自定义好的JS函数专门来转移实现原生消息发送相关函数,而后通过下载JS文件然后执行预定的代码尝试或达到替代原生代码过程)

    [self.jsRunner evaluateScript:@"action1(10);"];

    [self.jsRunner evaluateScript:@"action2([1,2,3,\‘你好哦\‘]);function testAction(){return 99;};"];

    JSValue *result = [self.jsRunner evaluateScript:@"testAction();"];

    NSLog(@"返回的结果:%@",result);

在UIWebView中获得JSContext,在代理OnFinshload函数中通过

self.jsRunner =[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

获得

在WKWebView中

You cannot obtain the context, because layout and javascript is handled on another process.Instead, add scripts to your webview configuration, and set your view controller (or another object) as the script message handler.- (void)setupWKWebView{ ???WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; ???// 设置偏好设置 ???config.preferences = [[WKPreferences alloc] init]; ???// 默认为0 ???config.preferences.minimumFontSize = 10; ???// 默认认为YES ???config.preferences.javaScriptEnabled = YES; ???// 在iOS上默认为NO,表示不能自动通过窗口打开 ???config.preferences.javaScriptCanOpenWindowsAutomatically = NO; ???config.processPool = [[WKProcessPool alloc] init]; ???config.userContentController = [[WKUserContentController alloc] init]; ???//注意在这里注入JS对象名称 "JSObjec" ???[config.userContentController addScriptMessageHandler:self name:@"JSObjec"]; ???????self.showWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; ???self.showWebView.navigationDelegate = self; ???[self.view addSubview:self.showWebView]; ???????NSURL *path = [NSURL fileURLWithPath:网页文件路径]; ???[self.showWebView loadRequest:[NSURLRequest requestWithURL:path]];}Now, send messages from JavaScript like so://在JS函数代码中调用//这里的内容差不多全部一样 只是调用的方法有区别 一定要注意区分 ???????????????//这个是用UIWebView时调用的方法 JSObjec.getCall(callInfo); ???????????????//下面是用WKWebView调用的方法 ???????????????window.webkit.messageHandlers.JSObjec.postMessage(callInfo);//当执行到上述语句是将回调下面这个函数Your script message handler will receive a callback:- (void)userContentController:(WKUserContentController *)userContentController ????????????????????????????didReceiveScriptMessage:(WKScriptMessage *)message{ ???NSLog(@"%@", message.body);}


普通的实现方式:
通过WebView调用页面中的JS函数,获得返回值
通过代理链接截获,执行原生代码

JS和webView的交互

原文地址:https://www.cnblogs.com/yuxiaoyiyou/p/8607919.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved