mui app embedded h5 web pages communicate with each other

Posted by kellog on Fri, 18 Feb 2022 11:30:40 +0100

problem

To make an app for mui, you need to open a web page on one of the pages. And the web page can get the user information of the current application.

solve

1. Create shell:

It's easy to open a web page in the page:

Create a shell with the following source code:

Shell functions include:

  1. Get the required parameters of the current page passed from the previous page, such as title
  2. Because when a page is opened by default, there will be a loading box. The shell monitors the loading status of the embedded web page. If the loading is completed within 2s, the loading box will be closed. Otherwise, the loading box will be closed automatically after 2s, so that the user can further operate, such as returning
  3. Monitor whether the web page has opened a new web page. For example, click an item on baidu home page to enter the web page of the item. If you click the return button in the upper left corner, the web page will return. Otherwise, close the current page directly
<!DOCTYPE HTML>
<html>
	<head>
		<meta charset="utf-8" />
		<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no,user-scalable=no" />
		<link rel="stylesheet" href="../../css/mui.css" />
		<link rel="stylesheet" href="../../css/iconfont.css" />
		<style type="text/css">
			* {
				touch-action: none;
			}

			#close_page {
				margin-left: 5px;
			}
		</style>
	</head>
	<body>
		<header class="mui-bar mui-bar-nav">
			<h1 class="mui-title" id="title"></h1>
			<a class="mui-icon mui-icon-left-nav mui-pull-left mui-action-back"></a>&nbsp;
			 <a href="javacript:void(0);" class="mui-icon iconfont icon-guanbi ruijie-font-large-x" style="color: #555555;margin-top: 5px;font-size: 17px!important;float: right;margin-right: auto;"
			  onclick="oldBack();"></a>
		</header>
		<script type="text/javascript" src="../../js/mui.js"></script>
		<script type="text/javascript" charset="utf-8">
			var ws = null,
				embed = null;
			var url = 'http://www.baidu.com';
			var type;
			var title;
			mui.plusReady(function() {
				// Get the parameter - title passed from the previous page
				ws = plus.webview.currentWebview();
				title = ws.title;
				if (title) {
					document.getElementById('title').innerText = title;
				}
				createEmbed();
			});
			// Create a subwebview
			function createEmbed() {
				embed = plus.webview.create(url, "url", {
					top: "44px",
					bottom: "0px",
					scalable: true
				});
				setTimeout(function() {
					//Add to the current webview to avoid right sliding back to blank
					ws.append(embed);
					embed.show();
					embed.setStyle({
						videoFullscreen: 'landscape',
						zindex: 100
					});
				}, 100);

				embed.addEventListener('loaded', function() {
					//Get the URL and title of the loaded page
					if (type) {
						url = embed.getURL();
						title = embed.getTitle();
						// If the page itself has a title, use the title of the page
						if (title) {
							document.getElementById('title').innerText = title;
						}
					}
					plus.nativeUI.closeWaiting();
				}, false);

				embed.addEventListener('loading', function() {}, false);
		
				// Up to two seconds, remove the mask to facilitate user fallback
				setTimeout(function() {
					plus.nativeUI.closeWaiting();
				}, 2000);
			}
			
			
			//Rewrite Mui Back method 
			var oldBack = mui.back;
			mui.back = function() {
				if(embed){
					embed.canBack(function(e) {
						var canBack = e.canBack;
						if (canBack) {
							embed.evalJS('window.history.go(-1);');
						} else {
							oldBack();
						}
					});
				}
			};
			
		</script>
	</body>
</html>

 

effect:

2. Shell and web communication

This is relatively simple and difficult. You need to understand the web page to get the shell context.

Conclusion: the web page in the app can directly obtain the context of the app. (so you can use the context, web page < -- context - > APP)

First, an api should be exposed in the app. The api returns the user information of the current app. An example is as follows:

2.1 add in the source code on the app:

/**
 * Get user information
 */
function getAppUser () {
	var user =  {name:'Lone ranger_A Tao',id:'008'}
	// embed has been defined in the above source code. The getAppUser method is an interface that needs to be implemented in advance in the web page
	embed.evalJS("getAppUser('" + JSON.stringify(user) + "')");
}

2.2 the embedded web page needs to do the following actions:

  • Implement getAppUser interface (refer to the communication logic diagram below for specific functions)
  • Introduce Mui js
  • Call the context of app in the plus environment (Note: the plus environment must be debugged on the real machine, so I always use the real machine for debugging, ^ ^ ^)

The demo code directly on the web page is as follows:

Precautions in the code:

  • Don't use let to define variables, otherwise you won't recognize this variable
  • Method definition: the method should be defined under the window object and explicitly defined
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no,user-scalable=no" />
    <title>I'm from the web title</title>
</head>
<body>
    <!--<button type="button" onclick="getAppUser()">Get current app User information for context</button>-->
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/mui/3.7.1/js/mui.min.js"></script>
<script>
    /**
     * Implement the getAppUser interface (it should be explicitly defined under the window object, otherwise an error will be reported)
     * @param userStr User information JSON string (because more than one user information may be returned, in order to expand the returned information without changing the interface, you choose to convert the user information into a string)
     */
    window.getAppUser = function (userStr) {
        alert(`Returned user information: ${userStr}`)
    }
    try {
        mui.plusReady(function() {
            // Get the current context of the web page. Don't use let to define variables. Use var, otherwise an error will be reported
            var wv = window.plus.webview.currentWebview().opener()
            // Method getAppUser of execution context (i.e. app)
            wv.evalJS("getAppUser()")
        })
    } catch (e) {
        alert('System abnormality')
    }

</script>
</html>

2.3 the above web pages are accessed using webstorm. Because they can be opened directly on the mobile phone, the following conditions need to be met:

  • The default port of webstom is modified and set to be accessible through the local ip address on a non local machine
    • The implementation method is as follows:
  • The mobile phone should be in the same LAN as the computer (the simplest way is to connect the mobile phone to the pc through usb. At this time, the computer will automatically use the hot network of the mobile phone)

The final effect is as follows:

 

 

Topics: mui