Run JavaScript Code in Webview

Run javascript code in Webview

From kitkat onwards use evaluateJavascript method instead loadUrl to call the javascript functions like below

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("var FunctionOne = function () {"
+ " try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
+ "};", null);
} else {
webView.loadUrl("javascript:"
+ "var FunctionOne = function () {"
+ " try{document.getElementsByClassName('test')[0].style.color='red';}catch(e){}"
+ "};");
}

Enable Javascript for your webview by adding the following line

wb.getSettings().setJavaScriptEnabled(true);

Run JavaScript in Android webview

Well I replaced:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}

with

webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView webview, String url) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}
}
});

and it just WORKS!

Run some Javascript in Flutter Webview

flutterWebviewPlugin.evalJavascript('<script language="JavaScript" type="text/javascript">alert("Hello World")</script>')

expects JavaScript, not HTML

<script language="JavaScript" type="text/javascript">alert("Hello World")</script>

is HTML.

Try

flutterWebviewPlugin.evalJavascript('alert("Hello World")')

How do I run javascript inside of an html string using webview?

You need to enable JavaScript for the WebView in it's WebSettings first.

        WebSettings webSettings = webView.getSettings();
if (webSettings != null) {
webSettings.setJavaScriptEnabled(true);
}

Also if you want to load HTML instead of a URL, you need to use loadData()instead of loadUrl().

public class MainActivity extends AppCompatActivity {

@SuppressLint("SetJavaScriptEnabled")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

WebView webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
if (webSettings != null) {
webSettings.setJavaScriptEnabled(true);
}

//Enable setWebContentsDebuggingEnabled to use Chrome DevTools in debug build
if (BuildConfig.DEBUG) {
WebView.setWebContentsDebuggingEnabled(true);
}

webView.addJavascriptInterface(this, "Android");

String page = "<html>" +
"<body>" +
"<h1>Test</h1>" +
"<script type=\"text/javascript\">" +
" document.write(Android.getDate());" +
"</script>" +
"</body>" +
"</html>";

webView.loadData(page, "text/html", "utf-8");
}

@JavascriptInterface
public String getDate() {
return "<p>The current date is " + new Date().toString() + "</p>";
}
}

unable to execute javascript code in Android WebView from Service

What kind of data you want to pass to Javascript? You could use the WebView.addJavascriptInterface() to "Plant" methods on the HTML document so you can call them from Javascript, invoke in native and return data back to Javascript. Will that help?

How to run javascript in a webview from Swift

You need to convert info in javascript alert into native UIAlert.

Add alert handler delegate described in WKUIDelegate.

func webView(_ webView: WKWebView,
runJavaScriptAlertPanelWithMessage message: String,
initiatedByFrame frame: WKFrameInfo,
completionHandler: @escaping () -> Void) {

let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let title = NSLocalizedString("OK", comment: "OK Button")
let ok = UIAlertAction(title: title, style: .default) { (action: UIAlertAction) -> Void in
alert.dismiss(animated: true, completion: nil)
}
alert.addAction(ok)
present(alert, animated: true)
completionHandler()
}

And call like below (there is a type in your code);

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("alert('hello from the webview')")
}

Sample Image



In Addition

There is a sample project that simulates two way communication between native and web in both way.

Run JavaScript in Android webview

Well I replaced:

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}

with

webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView webview, String url) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}
}
});

and it just WORKS!



Related Topics



Leave a reply



Submit