Can the PostMessage API be used to communicate with an Android WebView?

后端 未结 4 1391
小鲜肉
小鲜肉 2021-02-03 23:43

I usually use the HTML5 PostMessage API to communicate information from my iframed content to the parent frame. Recently I\'ve had my content used inside an Android WebView (as

4条回答
  •  面向向阳花
    2021-02-04 00:08

    You need to use an intermediate abstract interface that in one implementation processes messages via PostMessage and in another case via addJavascriptInterface.

    window.addEventListener("message", onReceivedPostMessage, false);
    
    function onReceivedPostMessage(event){
         //..ex deconstruct event into action & params
         var action = event.data.action;
         var params = event.data.params;
         performAction(action, params); //performAction would be the uniform API
    }
    
    function onReceivedActivityMessageViaJavascriptInterface(json){
         //..ex deconstruct data into action & params
         var data = JSON.parse(json); 
         var action = data.action;
         var params = data.params;
         performAction(action, params); //performAction would be the uniform API
    }
    

提交回复
热议问题