• Stars
    star
    105
  • Rank 328,196 (Top 7 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

This is a Tool, it use WKWebView to interact with H5

JKWKWebViewHandler

CI Status Version License Platform

Example

To run the example project, clone the repo, and run pod install from the Example directory first.

Requirements

Installation

JKWKWebViewHandler is available through CocoaPods. To install it, simply add the following line to your Podfile:

Object-C

pod "JKWKWebViewHandler"

Swift

pod "JKWKWebViewHandler_Swift"

article

Author

HHL110120, [email protected]

QQ Contact group

if you use QQ you can use this Qrcode to contact with us

developer guide

step 1

you should config the JKEventHandler

WKUserScript *usrScript = [[WKUserScript alloc] initWithSource:[JKEventHandler shareInstance].handlerJS injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    
    // 通过JS与webview内容交互
    config.userContentController = [[WKUserContentController alloc] init];
    
    [config.userContentController addUserScript:usrScript];
    // 注入JS对象名称AppModel,当JS通过AppModel来调用时,
    // 我们可以在WKScriptMessageHandler代理中接收到
    [config.userContentController addScriptMessageHandler:[JKEventHandler shareInstance] name:EventHandler];
   
    
    
    
    //通过默认的构造器来创建对象
    _webView = [[WKWebView alloc] initWithFrame:self.view.bounds
                                  configuration:config];
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_url]]];
    [self.view addSubview:_webView];

step 2

this is for JS developer

exec:function(plugin,funcName,params,successCallBack,failureCallBack){
 //when you want to call native function ,you should call this function with params.
 //plugin:the native className to handle the js func
 //funcName:the native funcName
 
 //params:this is the data you want to send to native.

 //successCallBack:this is the success block

 //failureCallBack:this is  the failure block

}

for Example:

function getInfoFromNative(){
var params = {'name':'我是jack!!!'};
JKEventHandler.exec('JKPluginA','getNativeInfo',params,function(data){
console.log('succedss block');
alert(data);
},
function(data){
console.log('fail block');
alert(data);
});
}

step 3

this is for native developer if you want interect with H5,you should create a plugin class and create the function the H5 specified to interected with you. for example:

#import <Foundation/Foundation.h>

@interface JKPluginA : NSObject
+ (void)getNativeInfo:(NSDictionary *)params :(void(^)(id response))successCallBack :(void(^)(id response))failureCallBack;
@end


#import "JKPluginA.h"

@implementation JKPluginA
+ (void)getNativeInfo:(NSDictionary *)params :(void(^)(id response))successCallBack :(void(^)(id response))failureCallBack{
NSLog(@"getNativeInfo %@",params);
if (successCallBack) {
successCallBack(@"success !!!");
}
if (failureCallBack) {
failureCallBack(@"failure !!!");
}
}
@end

swift guide

//step 1
func configureWKWebView() -> Void {
    self.eventHandler = JKEventHandlerSwift.init(webView, self)
    let config:WKWebViewConfiguration = WKWebViewConfiguration.init()
    config.preferences = WKPreferences.init()
    config.preferences.minimumFontSize = 10
    config.preferences.javaScriptEnabled = true
    config.preferences.javaScriptCanOpenWindowsAutomatically = true
    config.processPool = WKProcessPool.init()
    
    let usrScript:WKUserScript = WKUserScript.init(source: JKEventHandlerSwift.handleJS()!, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
    config.userContentController = WKUserContentController.init()
    config.userContentController.addUserScript(usrScript)
    config.userContentController.add(self.eventHandler, name: JKEventHandlerNameSwift)
    
    self.webView = WKWebView.init(frame: self.view.bounds, configuration: config)
    self.webView?.load(URLRequest.init(url: URL.init(string: self.url!)!))
    self.view.addSubview(self.webView!)
    self.eventHandler.webView = self.webView
    self.webView?.uiDelegate = self;
}

//step2
//MARK:JKEventHandlerProtocol
func nativeHandle(plugin: String?, funcName: inout String!, params: Dictionary<String, Any>?, success: ((Any?) -> Void)?, failure: ((Any?) -> Void)?) {
    if plugin == "JKPluginA" {
        JKPluginA.getNativeInfo(params: params ?? [:], successCallBack: success, failureCallBack: failure)
    }
}

//step3
class JKPluginA: NSObject {
     class func getNativeInfo(params:Dictionary<String,Any>, successCallBack:((_ response:Any?) -> Void)?, failureCallBack:((_ response:Any?) -> Void)?) -> Void {
        print("params:%@",params)
        if successCallBack != nil {
            successCallBack!("success !")
        }
        
        if failureCallBack != nil {
            failureCallBack!("failure !")
        }
    }
    
    
}

实现历程博客

《WKWebView与js交互之完美解决方案》

License

JKWKWebViewHandler is available under the MIT license. See the LICENSE file for more info.

More Repositories

1

JKRouter

this is a tool to help you to handle the push or pop between Viewcontrollers with your specified URL
Objective-C
47
star
2

JKUBS

this is a User Behavior Statistics tool.it can help you know user's behavior then adjust your app
Objective-C
24
star
3

JKDataHelper

this is a tool to help developer avoid the bug caused by the unstable API
Swift
20
star
4

JKTransferDataHelper

this is a tool to handle data transformation
Objective-C
17
star
5

JKSandBoxManager

the manager of sandbox,it contain the operations of sandbox
Objective-C
8
star
6

WCDBDemo

this is a demo of WCDB Demo,you can download to know how to use the WCDB
Objective-C++
4
star
7

JKUIHelper

this is a tool to help developer to draw UI easily such as shadow,roundCorner,the word link and so on.
Objective-C
4
star
8

JKCaptionsHelper

this is a helper of film subtitle and music subtitle
Swift
3
star
9

JKUBSAspects

this is a tool to help developer to method swizzle
Objective-C
3
star
10

JKNetworking

this is a network tool,it is reference YTKNetwork and depend on AFNetworking
Objective-C
3
star
11

JKKVOHelper

this is a tool to help develop to easily use KVO
Objective-C
3
star
12

JKAPIMock

this is a tool to help iOS developer mock API data to support parallel development
Objective-C
2
star
13

JKPacket

a swift lifecycle reponsable observe tool
Swift
1
star
14

JKPerformanceManager

Objective-C
1
star
15

JKAlertsManager

this is a alert manager,it handle the alert show sort
Swift
1
star
16

JKDateHelper

this is a date convert tool it help develop to convert date to string or convert string to date
Objective-C
1
star