如何在WKWebview中获取JS callBack?

时间:2016-09-20 09:11:28

标签: ios wkwebview

我在iOS中使用JSContext,并与js通信。我使用public typealias jsBridgeFuncAlias = (JSValue)->Void @objc protocol WebViewJSExport:JSExport { var call:jsBridgeFuncAlias?{get} } class SAJavaScriptBridge:NSObject,WebViewJSExport{ public var call: jsBridgeFuncAlias? public init(context:JSContext){ super.init() context.setObject(self, forKeyedSubscript:kBridgeName as (NSCopying & NSObjectProtocol)!) self.call = { [unowned self](block:JSValue) in self.callNativeMethod(block:block ) } } func callNativeMethod(block:JSValue){ block.call(withArguments:nil) //execute the js callback block in ios native } 来获取以下js回调:

WKWebView

但是在迁移到window.webkit.messageHandlers.WKWebView.postMessage(function()) 之后,我无法使用此代码获取js callBack块:

 $(function(){

var $newItemButton=$('#newItemButton');
var $newItemForm=$('#newItemForm');
var $textInput=$('#itemDescription');

  $newItemButton.show();
  $newItemForm.hide();
  $('#showForm').on('click',function(){

    $newItemButton.hide();
    $newItemForm.show();
 });

 $newItemForm.on('submit',function(e){
    e.preventDefault();
    var $newText=$('#itemDescription').val();
    $('li:last').after('<li>' + $newText + '</li>').val();
    $newItemForm.hide();
    $newItemButton.show();
    $textInput.val(' ');
 });
});

有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

我有一个简单的方法来解决这个问题,你可以将函数覆盖到字符串,就像这样

 const person = {
        firstName: "John",
        lastName: "Doe",
        age: 50,
        eyeColor: "blue",
    };

    function postMessage(message, callBack) {
        message.callBack = callBack.toString();
        window.webkit.messageHandlers.Native.postMessage(message);
    }


    document.getElementById("li1").onclick = function () {

        postMessage(person, function (args) {
            console.log('call back is invoked' );
            console.log(args);
        });

    };

在本机代码中,您可以获取callBack并执行js字符串。

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {

    if ([message.name isEqualToString:@"Native"]) {

        NSString *callBack = message.body[@"callBack"]; //get callBack
        NSDictionary *dict = @{
            @"key1": @"value1",
            @"key2": @"value2
        }; 

        id data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 
        [_webView evaluateJavaScript:[NSString stringWithFormat:@"(%@)(%@)", callBack, jsonString] completionHandler:^(id _Nullable jsData, NSError * _Nullable error) {

        }];
    }
}

但是有一点问题,你在js字符串函数中找不到thisthiswindow

答案 1 :(得分:0)

试试这个: window.webkit.messageHandlers.ur function.postMessage(ur object); 当你使用wkwebview时,你不应该使用javascripCore;

init config并添加u功能 [config.userContentController addScriptMessageHandler:委托名称:@&#34; u function&#34;];

当js调用该函数时,你可以获得乐趣: userContentController:didReceiveScriptMessage:;

答案 2 :(得分:0)

首先您需要注册回调-

enter image description here

然后倾听并处理 -

enter image description here

查看有关此主题的文章 https://medium.com/john-lewis-software-engineering/ios-wkwebview-communication-using-javascript-and-swift-ee077e0127eb