简体   繁体   English

如何在 WKWebview 中获取 JS 回调?

[英]How to get JS callBack in WKWebview?

I am using UIWebView in iOS, and communicate with js.我在 iOS 中使用UIWebView ,并与 js 通信。 I use JSContext to get the following js callback:我使用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
}

But after migrating to WKWebView , I cannot get js callBack block with this code:但是在迁移到WKWebView ,我无法使用以下代码获取 js callBack 块:

window.webkit.messageHandlers.WKWebView.postMessage(function())

Can anyone help?任何人都可以帮忙吗?

try this: window.webkit.messageHandlers.ur function.postMessage(ur object);试试这个:window.webkit.messageHandlers.ur function.postMessage(ur object); and when u use wkwebview,u should not use javascripCore;当你使用 wkwebview 时,你不应该使用 javascripCore;

init config and add u function [config.userContentController addScriptMessageHandler:delegate name:@"u function"];初始化配置并添加 u 函数 [config.userContentController addScriptMessageHandler:delegate name:@"u function"];

and when the js call the function,u can get in fun: userContentController:didReceiveScriptMessage:;当 js 调用函数时,你可以得到乐趣: userContentController:didReceiveScriptMessage:;

I have a simple way to resolve the question, you can cover the function to string, like this我有一个简单的方法来解决这个问题,你可以将函数覆盖到字符串,像这样

 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);
        });

    };

In you Native code, you can get the callBack and execute the js string.在您的 Native 代码中,您可以获取回调并执行 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) {

        }];
    }
}

But there is a little problem, you cant't get right this in js string function , this is window .但是有一个小问题,你不能在 js 字符串函数中得到thisthiswindow

1st you need to register for the callback -第一,您需要注册回调 -

在此处输入图片说明

And then listen for it and handle afterwards -然后倾听它并在之后处理 -

在此处输入图片说明

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM