如何解决“无法在'Window'上执行'postMessage':需要2个参数,但只有1个参数。”

时间:2018-08-16 00:40:10

标签: javascript react-native webview postmessage

我尝试启用react native webview和我的网页之间的通信。我终于找到了合适的解决方案here。但是,应用于我的项目的postMessage方法会引发以下错误。

  

无法在“窗口”上执行“ postMessage”:需要2个参数,但只有1个。

我发送以下参数:{"targetFunc":"handleDataReceived","data":1,"msgId":"00c28da3-f89c-244b-c7b7-3711d188ad60"}

.js中的代码:

export default class wvBridge {
constructor (){
    this.counter = 0;
}

callWvBridge() {      

    var promiseChain = Promise.resolve();

    var promises = {};
    var callbacks = {};

    var init = function() {

        const guid = function() {
            function s4() {
                return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
            }
            return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
        }

        window.webViewBridge = {
            /**
             * send message to the React-Native WebView onMessage handler
             * @param targetFunc - name of the function to invoke on the React-Native side
             * @param data - data to pass
             * @param success - success callback
             * @param error - error callback
             */
            send: function(targetFunc, data, success, error) {
                console.log('message send from website')
                success = success || function(){};
                error = error || function () {};

                var msgObj = {
                    targetFunc: targetFunc,
                    data: data || {},
                    msgId: guid(),
                };

                var msg = JSON.stringify(msgObj);

                promiseChain = promiseChain.then(function () {
                    return new Promise(function (resolve, reject) {
                        console.log("sending message " + msgObj.targetFunc);

                        promises[msgObj.msgId] = {resolve: resolve, reject: reject};
                        callbacks[msgObj.msgId] = {
                            onsuccess: success,
                            onerror: error
                        };

                        console.log(msg);
                        window.postMessage(msg);
                    })
                }).catch(function (e) {
                    console.error('rnBridge send failed ' + e.message);
                });
            },
        };          
    }
    init();
};  


icrHandler() {

    this.callWvBridge();

    this.counter++;

    window.webViewBridge.send('handleDataReceived', this.counter, function(res) {
        window.document.getElementById("button").setAttribute("style", "background-color: " + res);
    }, function(err) {
        window.document.getElementById("container").setAttribute("style", "background-color: " + err);
    });
}}

从我的角度来看,代码似乎很好。有人可以帮忙吗?

0 个答案:

没有答案