WKWebView 與 JS 交互簡單使用

通過調(diào)研,我決定使用WKWebView替換原來的UIWebView。
遇到的第一個問題就是WKWebView無法在我喜愛的xib上設(shè)置禽翼,通過翻墻搜索資料溪北,原來WKWebView沒有實現(xiàn)initWithCoder方法劳翰,自然也就找到了解決辦法:

自定義一個MyWebView生均,繼承自WKWebView

.h

#import <WebKit/WebKit.h>
@interface MyWebView : WKWebView
@end
.m

#import "MyWebView.h"

@implementation MyWebView

- (instancetype)initWithCoder:(NSCoder *)coder
{
    CGRect frame = [[UIScreen mainScreen] bounds];
    WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
    configuration.userContentController = [WKUserContentController new];
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    configuration.preferences = preferences;
    
    self = [super initWithFrame:frame configuration:configuration];
    self.translatesAutoresizingMaskIntoConstraints = NO;
    return self;
}

@end

這樣就可以像UIWebView一樣在xib設(shè)置約束了垫卤。



導(dǎo)入MyWebView评抚,投入使用

#import "WebViewController.h"
#import "MyWebView.h"

//1. 代理
@interface WebViewController ()<WKScriptMessageHandler, WKUIDelegate>

@property (strong, nonatomic) IBOutlet MyWebView *webView;

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    UIBarButtonItem *button = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"返回"]  style:UIBarButtonItemStylePlain target:self action:@selector(goBack)];
    self.navigationItem.leftBarButtonItem = button;
    
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlString]]];
    self.webView.UIDelegate = self;
    
    //JS調(diào)用OC:設(shè)置addScriptMessageHandler與name,并且設(shè)置<WKScriptMessageHandler>協(xié)議與協(xié)議方法
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"callNativeKaihu"];//開戶
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 移除handlers铛纬,防止內(nèi)存泄露
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"callNativeKaihu"];
}

- (void)goBack{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark - WKScriptMessageHandler
//OC在JS調(diào)用方法做的處理
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    // 打印所傳過來的參數(shù)模她,只支持NSNumber, NSString, NSDate, NSArray, NSDictionary, NSNull類型
    NSLog(@"JS調(diào)用了 %@ 方法,返回參數(shù) %@",message.name, message.body);
    if ([message.name isEqualToString:@"callNativeKaihu"]) {
        DRElectronicAccountVC *vc = [[DRElectronicAccountVC alloc]initWithNibName:@"DRElectronicAccountVC" bundle:nil];
        vc.dictionary = dic[@"data"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

WKWebView默認(rèn)禁止了一些跳轉(zhuǎn)

  • UIWebView
    打開www.apple.com/itunes/跳轉(zhuǎn)到appStore, 撥打電話, 喚起郵箱等一系列操作UIWebView默認(rèn)支持的。
  • WKWebView
    默認(rèn)禁止了以上行為,除此之外痛垛,js端通過alert()蹂析,彈窗的動作也被禁掉了俺祠。
    如何支持呢?

首先要設(shè)置WKWebView的WKUIDelegate肺然,并實現(xiàn)以下方法

#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    // js 里面的alert實現(xiàn)唇撬,如果不實現(xiàn),網(wǎng)頁的alert函數(shù)無效
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        completionHandler();
    }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
}

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    // js 里面的alert實現(xiàn),如果不實現(xiàn)晚唇,網(wǎng)頁的alert函數(shù)無效
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        completionHandler(YES);
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
        completionHandler(NO);
    }]];
    
    [self presentViewController:alertController animated:YES completion:^{}];
}

- (void)dealloc{
    NSLog(@"觀測web視圖釋放");
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末鸳粉,一起剝皮案震驚了整個濱河市湖雹,隨后出現(xiàn)的幾起案子纵装,更是在濱河造成了極大的恐慌滤祖,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,607評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡痘括,警方通過查閱死者的電腦和手機(jī)嚣潜,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,239評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來丧诺,“玉大人呵晚,你說我怎么就攤上這事芯急。” “怎么了杖挣?”我有些...
    開封第一講書人閱讀 164,960評論 0 355
  • 文/不壞的土叔 我叫張陵氓皱,是天一觀的道長。 經(jīng)常有香客問我垢揩,道長绝淡,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,750評論 1 294
  • 正文 為了忘掉前任订咸,我火速辦了婚禮神郊,結(jié)果婚禮上带欢,老公的妹妹穿的比我還像新娘雄右。我一直安慰自己乡括,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,764評論 6 392
  • 文/花漫 我一把揭開白布栅受。 她就那樣靜靜地躺著屏镊,像睡著了一般痰腮。 火紅的嫁衣襯著肌膚如雪膀值。 梳的紋絲不亂的頭發(fā)上沧踏,一...
    開封第一講書人閱讀 51,604評論 1 305
  • 那天翘狱,我揣著相機(jī)與錄音,去河邊找鬼赚导。 笑死吼旧,一個胖子當(dāng)著我的面吹牛黍少,可吹牛的內(nèi)容都是我干的厂置。 我是一名探鬼主播魂角,決...
    沈念sama閱讀 40,347評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼访忿,長吁一口氣:“原來是場噩夢啊……” “哼海铆!你這毒婦竟也來了卧斟?” 一聲冷哼從身側(cè)響起憎茂,我...
    開封第一講書人閱讀 39,253評論 0 276
  • 序言:老撾萬榮一對情侶失蹤板乙,失蹤者是張志新(化名)和其女友劉穎募逞,沒想到半個月后凡辱,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體栗恩,經(jīng)...
    沈念sama閱讀 45,702評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡乳乌,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,893評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了磷瘤。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片搜变。...
    茶點故事閱讀 40,015評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡扳抽,死狀恐怖贸呢,靈堂內(nèi)的尸體忽然破棺而出拢军,到底是詐尸還是另有隱情茉唉,我是刑警寧澤赌渣,帶...
    沈念sama閱讀 35,734評論 5 346
  • 正文 年R本政府宣布览芳,位于F島的核電站鸿竖,受9級特大地震影響缚忧,放射性物質(zhì)發(fā)生泄漏闪水。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,352評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望衡招。 院中可真熱鬧始腾,春花似錦浪箭、人聲如沸山林。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,934評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽明也。三九已至温数,卻和暖如春撑刺,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背甫菠。 一陣腳步聲響...
    開封第一講書人閱讀 33,052評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留痰洒,地道東北人丘喻。 一個月前我還...
    沈念sama閱讀 48,216評論 3 371
  • 正文 我出身青樓仓犬,卻偏偏與公主長得像搀继,于是被迫代替她去往敵國和親叽躯。 傳聞我的和親對象是個殘疾皇子肌括,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,969評論 2 355

推薦閱讀更多精彩內(nèi)容