RunJavaScript examples. Ascii. PrettyJson. Evaluate. indexOf. Countdown

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);

4 Likes

- App.

p51d_runjavascript.aia (4.5 KB)

- Designer.

- Block.

5 Likes

:+1:
Better plus 1 for result of indexOf, since ai is 1 based.

11.- Get time from Internet.

RunJavaScript:

fetch('https://worldtimeapi.org/api/timezone/Europe/Madrid')
.then( function(response) {
response.text().then(function(data) {AppInventor.setWebViewString("" + data.toString()); });
})
.catch(function(err) {AppInventor.setWebViewString("Error");});

Time zone:

https://worldtimeapi.org/api/timezone

12.- Fibonacci sequence.

https://en.wikipedia.org/wiki/Fibonacci_number

RunJavaScript:

terms = 15;
n1 = 0; 
n2 = 1;
f = "";

for (i = 1; i <= terms; i++) {
    f = f + n1.toString() + "-";
    next = n1 + n2;
    n1 = n2;
    n2 = next;
}
AppInventor.setWebViewString(f);

13.- Sound.

  • When you press a button, the note "la" (A) should sound.

var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
var frequency = 440;
var oscillator = audioCtx.createOscillator();
oscillator.frequency.setValueAtTime(frequency, audioCtx.currentTime);
oscillator.connect(audioCtx.destination);
oscillator.start();
setTimeout(function() {
  oscillator.stop();
}, 500);
**Credits: GPT-2**

3 Likes

14.- Regex in JavaScript.

1 Like

15.- String to Hex.

str = 'Hola';  
hex = '';  
 for (i = 0; i < str.length; i++) {hex += str.charCodeAt(i).toString(16).padStart(2, '0'); };

javascript_string_hex

2 Likes