前言
最近幾年混合開(kāi)發(fā)越來(lái)越火,今天想寫(xiě)一個(gè)wkwebview和cordova的交互走贪。
1: 創(chuàng)建第一個(gè)Cordova工程
打開(kāi)終端,cmd切換目錄到工作目錄下谅阿,輸入以下命令,同樣,可能需要點(diǎn)時(shí)間來(lái)完成
cordova create Demo com.cordova.demo.hello HelloWorld
2: 添加平臺(tái)支持
所有后續(xù)命令在項(xiàng)目的目錄中進(jìn)行纸兔,可在該項(xiàng)目任何子目錄中奈揍,cmd切換到項(xiàng)目目錄下
cd Demo
在構(gòu)建項(xiàng)目之前,你需要指定一組目標(biāo)平臺(tái)话原。你能夠運(yùn)行這些命令取決于您的機(jī)器是否支持每一個(gè)SDK晤揣,合理是否已安裝SDK。在MAC上運(yùn)行命令:
cordova platform add ios
3: 查看Cordova支持平臺(tái)以及已經(jīng)添加的平臺(tái)
cordova platforms ls
4: 添加插件
cordova plugin add cordova-plugin-device
5: 查看插件
cordova plugin list
6: 添加wkwebview插件
cordova plugin add cordova-plugin-wkwebview-engine
7: 在iOS項(xiàng)目,并使用cocoapods在,podfile文件如下,pod install
platform :ios,'9.0'
inhibit_all_warnings!
target 'WKWebiveCordova' do
pod 'cordova-plugin-device'
pod 'cordova-plugin-wkwebview-engine
end
8 :拉入www文件進(jìn)入iOS項(xiàng)目
在(cordova項(xiàng)目)下面兩個(gè)標(biāo)記出來(lái)的文件和文件夾移動(dòng)到(iOS項(xiàng)目)中,注意是(cordova項(xiàng)目)/platforms/ios文件夾下面的被我整理下目錄結(jié)構(gòu)朱灿。拉入ios項(xiàng)目昧识,記得這樣勾選create folder references,才會(huì)變成藍(lán)色文件夾
9: 查看藍(lán)色文件夾目錄,其中只有platform下的android是安卓那邊的母剥,其他文件夾都是和安卓公用滞诺,等下交互的方法名要一樣。
10: config.xml配置說(shuō)明
<content src="index.html" />
本地的配置的idnex.html环疼,啟動(dòng)wkwebview习霹,如果startPage 沒(méi)有寫(xiě)則是默認(rèn)啟動(dòng)這個(gè)html文件。
加載wkwebview時(shí)候炫隶,要記得載入config.xml文件淋叶,代碼下面會(huì)顯示
跳轉(zhuǎn)url界面能顯示出來(lái)配置如下東西:
<feature name="IntentAndNavigationFilter">
<param name="ios-package" value="CDVIntentAndNavigationFilter" />
<param name="onload" value="true" />
</feature>
<feature name="CDVWKWebViewEngine">
<param name="ios-package" value="CDVWKWebViewEngine" />
</feature>
<allow-navigation href="http://*/*" />
<allow-navigation href="https://*/*" />
<allow-navigation href="*" />
<preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
<plugin name="cordova-plugin-wkwebview-engine" spec="^1.2.1" />
11: 新建一個(gè)WKWebview文件繼承CDVViewController 來(lái)顯示加載wkwebview
WKWebview.h文件如下
#import <WebKit/WebKit.h>
#import <UIKit/UIKit.h>
#import <Cordova/CDVViewController.h>
#import <Cordova/CDVCommandDelegateImpl.h>
#import <Cordova/CDVCommandQueue.h>
NS_ASSUME_NONNULL_BEGIN
@interface WKWebview : CDVViewController
+ (WKWebview *)shareInstance;
//設(shè)置這個(gè)值,加載當(dāng)前頁(yè)面
@property (nonatomic, copy) NSString *webUrl;
//當(dāng)前頁(yè)面webview
@property (nonatomic, strong) WKWebView *currentWebView;
@end
NS_ASSUME_NONNULL_END
WKWebview.m文件如下
#import "WKWebview.h"
@interface WKWebview ()
@end
@implementation WKWebview
- (instancetype)init {
self = [super init];
if (self) {
self.configFile = [self configPath];
}
return self;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onNotification:)
name:CDVPluginResetNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(onNotificationed:)
name:CDVPageDidLoadNotification object:nil];
[self setWebViewBackground];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view
self.currentWebView = (WKWebView *)self.webView;
self.webView.backgroundColor = [UIColor redColor];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:CDVPluginResetNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:CDVPageDidLoadNotification object:nil];
}
- (NSString *)configPath {
NSString *path = [[NSBundle mainBundle]pathForResource:@"config" ofType:@"xml"];
NSLog(@"path===== %@", path);
return path;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)onNotification:(NSNotification *)notification {
NSLog(@"webview開(kāi)始加載");
WKWebView *webview = notification.object;
if (![[webview.URL absoluteString] containsString:@"www/error.html"]) {
}
if ([webview.URL.absoluteString isEqualToString:@"ios:backtotheroot"]) {
[self.navigationController popViewControllerAnimated:YES];
}
}
//wkwebView
- (void)onNotificationed:(NSNotification *)notification {
NSLog(@"webview加載完成");
WKWebView *webview = notification.object;
//去除長(zhǎng)按后出現(xiàn)的文本選取框
[webview evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:^(id obj, NSError *error){
}];
[webview evaluateJavaScript:@"document.title" completionHandler:^(id obj, NSError *error) {
if ([obj isKindOfClass:[NSString class]]) {
self.title = (NSString *)obj;
}
}];
}
- (void)setWebUrl:(NSString *)webUrl {
if (!webUrl) {
return;
}
_webUrl = webUrl;
if (self.currentWebView) {
NSURL *url = [NSURL URLWithString:[webUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.currentWebView loadRequest:request];
}
}
- (void)setWebViewBackground {
NSLog(@"self.startPage==%@", self.startPage);
if ([self.startPage containsString:@"hsjob"]) {
self.view.backgroundColor = [UIColor redColor];
} else if ([self.startPage containsString:@"hstravel"]) {
self.view.backgroundColor = [UIColor redColor];
} else if ([self.startPage containsString:@"movie"]) {
self.view.backgroundColor = [UIColor blackColor];
}
}
@end
12: 啟動(dòng)遠(yuǎn)程url顯示wkwenview界面調(diào)用
WKWebview *vc = [[WKWebview alloc] init];
vc.startPage = @"http://www.baidu.com";
vc.hidesBottomBarWhenPushed = NO;
[self.navigationController pushViewController:vc animated:YES];
13: 把vc.startPage = @"http://www.baidu.com"; 屏蔽掉伪阶,默認(rèn)顯示出index.html煞檩,用來(lái)實(shí)現(xiàn)原聲和html的交互demo
14: 新建一個(gè)CDVPlugin繼承CDVPlugin 來(lái)作為原聲和html5的橋接調(diào)用
MyPlugi.h文件
#import "CDVPlugin.h"
#import <Cordova/CDVPlugin.h>
NS_ASSUME_NONNULL_BEGIN
@interface MyPlugin : CDVPlugin
// 獲取當(dāng)前位置信息
- (void)currentPosition:(CDVInvokedUrlCommand *)command;
@end
NS_ASSUME_NONNULL_END
MyPlugi.m文件
#import "MyPlugin.h"
@implementation MyPlugin
//獲取當(dāng)前位置信息
- (void)currentPosition:(CDVInvokedUrlCommand *)command {
NSLog(@"command是回調(diào)的參數(shù),在里面取");
CDVPluginResult *result2 = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsArray:@[ @"data1", @"data2" ]];
[self.commandDelegate sendPluginResult:result2 callbackId:command.callbackId];
}
@end
15: 在config.xml文件配置下這個(gè)文件如下
<feature name="MyPlugin">
<param name="ios-package" value="MyPlugin" />
</feature>
16: index.html文件配置如下
<script type="text/javascript" src="./platform/common/loader.js"></script> // 能并行執(zhí)行js
<script type="text/javascript">
var loadList = ["./platform/common/hsplatform.js"];
var u = navigator.userAgent;
var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android終端
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
//app內(nèi)部 這里需要判斷加載安卓或者ios的區(qū)別栅贴,我就默認(rèn)為ios了
if (u.indexOf("_hsApp_") != -1) {
var cordovaURL = "./platform/ios/cordova.js";
if (isiOS) {
cordovaURL = "./platform/ios/cordova.js";
}
loadList.push(cordovaURL, "./js/index.js");
}else{
var cordovaURL = "./platform/ios/cordova.js";
if (isiOS) {
cordovaURL = "./platform/ios/cordova.js";
}
loadList.push(cordovaURL, "./js/index.js");
}
Loader.load(loadList);
</script>
17: 修改下index.js文件
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log("準(zhǔn)備");
}
// 獲取當(dāng)前位置
Cordova.exec(successCurrentPosition, errorCurrentPosition, "MyPlugin", "currentPosition", [argument]);
/ ***successCurrentPosition 成功回調(diào)
errorCurrentPosition 失敗回調(diào)
MyPlugin 我們新建的文件名字
currentPosition 調(diào)用方法
argument 入?yún)?**/
function currentPosition() {
console.log("該功能只能在A(yíng)PP內(nèi)部使用");
var argument = JSON.stringify({
'relocation': 'false'
});
Cordova.exec(successCurrentPosition, errorCurrentPosition, "MyPlugin", "currentPosition", [argument]);
}
//獲取當(dāng)前位置成功回調(diào)
function successCurrentPosition(position) {
console.log(position);
}
//獲取當(dāng)前位置失敗回調(diào)
function errorCurrentPosition(position) {
console.log(position);
}
18: 為了index.js能正常打印console.log,在index.html上加上
<script src="https://cdn.bootcss.com/vConsole/3.2.0/vconsole.min.js"></script>
在config.xml配置
<feature name="Console">
<param name="ios-package" value="CDVLogger" />
<param name="onload" value="true" />
</feature>
19: 點(diǎn)擊h5界面 實(shí)現(xiàn)使用原生的交互如下斟湃,打印出
2022-07-07 05:05:57.442579+0800 WKWebiveCordova[74344:646107] 該功能只能在A(yíng)PP內(nèi)部使用
2020-07-07 05:05:57.445205+0800 WKWebiveCordova[74344:646107] command是回調(diào)的參數(shù),在里面取
2020-07-07 05:15:08.682174+0800 WKWebiveCordova[74813:651778] error==data1,data2