Latest 1.2.0
Homepage https://github.com/zhszy/WKWebViewJSDemo
License MIT
Platforms ios 8.0, requires ARC
Authors

WKWebViewJSDemo

Do you know how to do this in Android? You simply need to create a class and pass an instance to the WebView through addJavascriptInterface(Object object, String name).

Installation with CocoaPods

CocoaPods is a dependency manager for Objective-C, You can install it with the following command:

$ gem install cocoapods

CocoaPods 0.39.0+ is required to build AFNetworking 3.0.0+.

Podfile

To integrate WKWebViewJSBridge into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/zhszy/Speccs.git
platform :ios, '8.0'

target 'TargetName' do
pod 'WKWebViewJSBridge'
end

Then, run the following command:

$ pod install

Some code to demonstrate

So basically what you need to do is create a class like this.

@interface MyJSInterface : NSObject

- (void) test;
- (void) testWithParam: (NSString*) param;
- (void) testWithTwoParam: (NSString*) param AndParam2: (NSString*) param2;

- (NSString*) testWithRet;

@end

Then add the interface to your UIWebView.

MyJSInterface* interface = [MyJSInterface new];
[self.myWebView addJavascriptInterfaces:interface WithName:@"MyJSTest"];
[interface release];

In Javascript, you can call the Objective-C methods by this simple code.

MyJSTest.test();
MyJSTest.testWithParam("ha:ha");
MyJSTest.testWithTwoParamAndParam2("haha1", "haha2");

var str = MyJSTest.testWithRet();

Just that simple!!! EasyJSWebView will help you do the injection. And you do not even need to use async-style writing to get the return value!!!

But of course, sometimes we may need to use the async-style code. It is also supported. You can even get the return value from the callback function.

- (void) testWithFuncParam: (EasyJSDataFunction*) param{
  NSLog(@"test with func");

    NSString* ret = [param executeWithParam:@"blabla:"bla"];

    NSLog(@"Return value from callback: %@", ret);
}

And in Javascript,

MyJSTest.testWithFuncParam(function (data){
    alert(data); //data would be blabla:"bla
    return "some data";
});

注:此项目参考EasyJSWebView进行封装

Latest podspec

{
    "name": "WKWebViewJSBridge",
    "version": "1.2.0",
    "summary": "You simply need to create a class and pass an instance to the WebView through addJavascriptInterface(Object object, String name).",
    "authors": {
        "zhszy": "[email protected]"
    },
    "homepage": "https://github.com/zhszy/WKWebViewJSDemo",
    "license": {
        "type": "MIT",
        "file": "LICENSE"
    },
    "platforms": {
        "ios": "8.0"
    },
    "source": {
        "git": "https://github.com/zhszy/WKWebViewJSDemo.git",
        "tag": "1.2.0"
    },
    "requires_arc": true,
    "source_files": "WKWebViewJSBridge"
}

Pin It on Pinterest

Share This