可以通过本地文件、url 等方式。
- NSString *htmlPath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
- NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlPath]];
- [self.webView loadRequest:request];
Native 调用 JS 是通过 UIWebView 的 stringByEvaluatingJavaScriptFromString 方法实现的,该方法返回 js 脚本的执行结果。
- [webView stringByEvaluatingJavaScriptFromString: @"Math.random();"];
实际上就是调用了网页的 Window 下的一个对象。如果我们需要让 native 端调用 js 方法,那么这个 js 方法必须在 window 下可以访问到。
反过来,JavaScript 调用 Native,并没有现成的 API 可以调用,而是间接地通过一些其它手段来实现。UIWebView 有个代理方法:在 UIWebView 内发起的任何网络请求都可以通过 delegate 函数在 Native 层得到通知。由此思路,我们就可以在 UIWebView 内发起一个自定义的网络请求,通常是这样的格式:jsbridge://methodName?param1=value1¶m2=value2...
在 UIWebView 的 delegate 函数中,我们判断请求的 scheme,如果 request.URL.scheme 是 jsbridge,那么就不进行网页内容的加载,而是去执行相应的方法。方法名称就是 request.URL.host。参数可以通过 request.URL.query 得到。
问题来了??
发起这样 1 个网络请求有 2 种方式。1:location.href .2:iframe。通过 location.href 有个问题,就是如果 js 多次调用原生的方法也就是 location.href 的值多次变化,Native 端只能接受到最后一次请求,前面的请求会被忽略掉。
使用 ifrmae 方式,以调用 Native 端的方法。
- var iFrame;
- iFrame = document.createElement("iframe");
- iFrame.style.height = "1px";
- iFrame.style.width = "1px";
- iFrame.style.display = "none";
- iFrame.src = url;
- document.body.appendChild(iFrame);
- setTimeout(function() {
- iFrame.remove();
- },
- 100);
举个
来源: https://juejin.im/post/5a3b06d85188257d6a7eb5b0