I am busy developing a mini-program using VodaPay mini-programs and rendering my web-page in an H5 web-view.
I have imported the CDN and it works correctly in the Simulator and while running on device on the VodaPay super-app. But when running on device I get the following error:
my is not defined
How do I prevent this from occurring? And why does this issue occur?
<script type="text/javascript" src="https://appx/web-view.min.js"></script>
<script>
// Sends message to VodaPay Mini-Program.
my.postMessage({name:"test web-view"});
// Did receive message from VodaPay Mini-Program.
my.onMessage = function(e) {
console.log(e); // {'sendToWebView': '1'}
}
</script>
The Web-View cdn will only run when your mini-app is running on device or in the Simulator. Therefore it is necessary to first check if the my. library is available in order to establish that it's running in a Mini-Program context.
<!-- MINI: Used to communicate with mini app. Have to include the script body here otherwise we get my. not recognized errors <START>-->
<script src="https://appx/web-view.min.js"></script>
<script id="messageSend">
function sendMessage(data) {
//If not in mini app webview then my. throws errors
try {
my.postMessage(data);
} catch(error) {
//Prevent my. from throwing error in browser
}
}
</script>
<script id="messageReceive">
try {
//Store message in session storage, and then change messageReceiveListener innerText to trigger a mutation event to notify that a message has arrived.
my.onMessage = function (e) {
sessionStorage.setItem('message',JSON.stringify(e));
document.getElementById('messageReceiveListener').innerText = e;
}
sessionStorage.setItem('inMiniProgram',true);
} catch(error){ //Prevent my. from throwing error in browser
sessionStorage.setItem('inMiniProgram',false);
}
</script>
<input id="messageReceiveListener" hidden></input>
<!-- MINI:<END> -->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With