Run javascript without ui
// private WebView jsEngineWebview;
// Initialize the WebView and enable JavaScript jsEngineWebview = new WebView(this); jsEngineWebview.getSettings().setJavaScriptEnabled(true); jsEngineWebview.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { } }); jsEngineWebview.loadUrl("about:blank"); // Load a blank page
button1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View _view) { javascriptCode = "// javascript code\n\n// Function to calculate sum of two numbers\nfunction calculateSum(a, b) {\n var result = a + b; // Declare a variable to hold the sum\n return result; // Return the sum\n}\n\n// Use the function with example numbers\nvar number1 = 5; // Declare first number\nvar number2 = 3; // Declare second number\nvar sum = calculateSum(number1, number2); // Call the function and store the result\n\nvar final_result = sum;\nfinal_result; // Return the \"final_result\" as the final result of the script"; // Execute JavaScript jsEngineWebview.evaluateJavascript(javascriptCode, new ValueCallback<String>() { @Override public void onReceiveValue(String value) { // Remove quotes around the result if necessary outputOfJavascript = value.replaceAll("^\"|\"$", ""); SketchwareUtil.showMessage(getApplicationContext(), outputOfJavascript); } }); } });
©2025 Sketchub | User Policy