How to test for the presence of the webViewString object?

What ?

When a webviewer component is initialised and a web page loaded, AI2 introduces a new window object, the WebViewString, to allow developers / users to pass information (as a string) to and from the web page. This is all well and good, but sometimes your html/web page, needs to know if it can use the WebViewString, or not.

Why ?

  • The web page is hosted online, and if accessed outside of the AI2 app, will not have access to the WebViewString. You can provide an alternate route for the data access and storage, e.g. localStorage or a url.
  • When developing your html, you can test the html without having to continually upload a new html file to your aia project

How?
I was ably assisted by @Kevinkun in finding the solution: we needed to identify whether the window.AppInventor object existed or not, then simply use an if/else in javascript.

The example below shows how it is done. The web page is online, but can be used inside an app to interact with the app via the webviewstring, or used externally on any browser to return similar output. The use of notifier and alert are for demo purposes.

HTML

<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

<head>
	<title>Is WebViewString</title>
	
</head>

<body>
	<h2>Is there a WebViewString ?</h2>
	<p>Click on the Run Msg button below to find out!</p>
	<button id="show" onclick="runMsg()">Run Msg</button>
	<script>
	
	var msg;
	
	function runMsg() {
	if( window.AppInventor ){
				msg = "This message has come from the example web page, and is being displayed in an AI2 notifier inside the app.";
				window.AppInventor.setWebViewString(msg); 
				}
			else {
				msg = "This message has come from the example web page, and is being displayed in a javascript alert, because there is no webviewstring."
				alert(msg);
			}
	}
	</script>
</body>

</html>

AIA PROJECT
isWVS.aia (2.1 KB)

ONLINE URL (try from your computer)
https://carter-computing.co.uk/iswvs.html

2 Likes

(added to FAQ)