1<html> 2<!-- Copyright 2022 The Android Open Source Project 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15--> 16<head> 17 <script type="text/javascript"> 18 let timestamp = 0; 19 let messagePort; 20 21 function onNativeMessage(event) { 22 let i = 0; 23 const data = event.data; 24 if (typeof data === 'string') { 25 i = parseInt(event.data); 26 messagePort.postMessage(i.toString()); 27 } else if (data instanceof ArrayBuffer) { 28 i = new DataView(event.data).getInt32(0, false); 29 const buffer = new ArrayBuffer(4); 30 new DataView(buffer).setInt32(0, i, false); 31 messagePort.postMessage(buffer, [buffer]); 32 } else { 33 // Invalid type 34 console.error(`Invalid type: ${typeof data}`); 35 } 36 if (i % 100 === 0) { 37 const counterInfo = `${i} messages sent.`; 38 document.getElementById("result").innerHTML = counterInfo; 39 } 40 } 41 42 window.onmessage = (e) => { 43 if (e.ports[0]) { 44 messagePort = e.ports[0]; 45 messagePort.onmessage = onNativeMessage; 46 document.getElementById("port").style = ""; 47 } else { 48 onNativeMessage(e); 49 } 50 } 51 </script> 52</head> 53<body> 54 <h1>Web content (within WebView)</h1> 55 <div> 56 <p id="port" style="display: none;">MessagePort set</p> 57 </div> 58 <div> 59 <span>Message from app: </span> 60 <span id="result" style="color:red">Not received.</span> 61 </div> 62</body> 63</html> 64