Cookies with JavaScript. WebViewer

We are going to create and read cookies in the WebViewer using JavaScript.

We consult this tutorial:
https://www.w3schools.com/js/js_cookies.asp

We load these codes into the app:

cookie_set.htm

<script>
// Example: cname_cvalue: "age=24"
cname_cvalue = window.AppInventor.getWebViewString(); // INPUT
document.cookie = cname_cvalue + ";expires=Sat, 18 Dec 2038 12:00:00 UTC;domain=localhost;path=/";
</script>

cookie_get.htm

<script>
function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i <ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

cname = window.AppInventor.getWebViewString(); // INPUT
AppInventor.setWebViewString(getCookie(cname)); // OUTPUT
</script>

  • Note that we can pass the cookie from one WebViewer to another and in different Screens.
  • In this example we introduce cookies using
    key=value

p170C_Cookies_JS_v1.aia (5.3 KB)

2 Likes

We can also use the RunJavaScript block.

p170C_Cookies_JS_v2.aia (2.7 KB)