JavaScript synchronous native communication to WKWebView

前端 未结 4 540
我在风中等你
我在风中等你 2020-11-29 23:21

Is synchronous communication between JavaScript and Swift/Obj-C native code possible using the WKWebView?

These are the approaches I have tried and have failed.

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 00:03

    I was facing a similar issue, i resolved it by storing promise callbacks.

    The js that you load in your web view via WKUserContentController::addUserScript

    var webClient = {
        id: 1,
        handlers: {},
    };
    
    webClient.onMessageReceive = (handle, error, data) => {
        if (error && webClient.handlers[handle].reject) {
            webClient.handlers[handle].reject(data);
        } else if (webClient.handlers[handle].resolve){
            webClient.handlers[handle].resolve(data);
        }
    
        delete webClient.handlers[handle];
    };
    
    webClient.sendMessage = (data) => {
        return new Promise((resolve, reject) => {
           const handle = 'm' + webClient.id++;
           webClient.handlers[handle] = { resolve, reject };
           window.webkit.messageHandlers..postMessage({data: data, id: handle});
       });
    }
    

    Perform Js Request like

    webClient.sendMessage().then((response) => {
    ...
    }).catch((reason) => {
    ...
    });
    

    Receive request in userContentController :didReceiveScriptMessage

    Call evaluateJavaScript with webClient.onMessageReceive(handle, error, response_data).

提交回复
热议问题