RunJavaScript is a block of the WebViewer component.
Let's see several examples with this block.
1.- Get ASCII of 'R'.
AppInventor.setWebViewString('R'.codePointAt(0));
2.- Get char 83.
AppInventor.setWebViewString(String.fromCodePoint(83));
3.- Obtain the hypotenuse using the Pythagorean theorem.
a = 3.47;
b = 4.71;
hypotenuse = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)) ;
AppInventor.setWebViewString("" + hypotenuse);
4.- Get 5 random cards.
from: JavaScript Program to Shuffle Deck of Cards
const suits = ["Spades", "Diamonds", "Club", "Heart"];
const values = [
"Ace",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"Jack",
"Queen",
"King",
];
let deck = [];
for (let i = 0; i < suits.length; i++) {
for (let x = 0; x < values.length; x++) {
let card = { Value: values[x], Suit: suits[i] };
deck.push(card);
}
}
for (let i = deck.length - 1; i > 0; i--) {
let j = Math.floor(Math.random() * i);
let temp = deck[i];
deck[i] = deck[j];
deck[j] = temp;
}
var out = "";
for (let i = 0; i < 5; i++) {
out = out + `${deck[i].Value} of ${deck[i].Suit},`;
};
AppInventor.setWebViewString(out);
5.- Present in Pretty Json, that is, in an easily readable format.
from: How to pretty print JSON string in JavaScript ? - GeeksforGeeks
var obj = {"prop_1": {"prop_11": "val_11", "prop_12": "val_12" }, "prop_2": "val_2","prop_3": "val_3" };
salida = JSON.stringify(obj, undefined, 4);
AppInventor.setWebViewString(salida);
6.- Countdown. (Just press this button once).
from: JavaScript Program to Create Countdown Timer
// let countDownDate = new Date("Aug 5, 2025 14:22:36").getTime();
// let countDownDate = new Date().getTime() + 24 * 60 * 60 * 1000;
alert("Start.");
let countDownDate = new Date().getTime() + 60 * 1000;
let x = setInterval(function() {
let now = new Date().getTime();
let timeLeft = countDownDate - now;
const days = Math.floor( timeLeft/(1000*60*60*24) );
const hours = Math.floor( (timeLeft/(1000*60*60)) % 24 );
const minutes = Math.floor( (timeLeft/1000/60) % 60 );
var seconds = Math.floor( (timeLeft/1000) % 60 );
if (seconds < 0) {
clearInterval(x);
alert("CountDown Finished.");
};
AppInventor.setWebViewString(seconds);
}, 2000);
7.- Validate email address.
from: JavaScript Program to Validate An Email Address
email_id = 'abc123@gmail.com';
const regex_pattern = /^(([^<>()[]\.,;:\s@"]+(.[^<>()[]\.,;:\s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
if (regex_pattern.test(email_id)) {
AppInventor.setWebViewString('The email address is valid');
}
else {
AppInventor.setWebViewString('The email address is not valid');
}
8.- indexOf.
https://www.w3schools.com/jsref/jsref_indexof.asp
texto = 'This is text';
out = texto.indexOf('is');
AppInventor.setWebViewString(out);
9.- Evaluate expression.
with (Math) {result = eval('log(6) / cos(6) + sqrt(25)');}
AppInventor.setWebViewString("" + result);
10. Prompt.
var name = prompt("What's your name?"); AppInventor.setWebViewString(name);