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')")
}
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
How to Detect Which CSS Grid Column and Row an Element Is in Using JavaScript
Grunt Plugin for Assets Versioning
How to Check If Text Is Truncated by CSS Using JavaScript
Replacing Normal File Upload Input with an Image
How to Prevent Material Icon Text from Showing Up When Google's Js Fails to Convert Them
Screen Zooms in When a Bootstrap Modal Is Opened on iOS 9 Safari
Detect Support for Background-Attachment: Fixed
Position Sticky: Scrollable, When Longer Than Viewport
How to Handle Radio Event When Icheck-Helper Is Used
Primefaces Dialog with Modal=True Not Working Properly
Gulp Less Not Handling Includes Properly, Included Variables Not Defined
How to Parse CSS Font Shorthand Format
Amcharts - Line Chart Overflowing Graph Container
CSS Class Selector Styles Not Being Applied in React Project
How to Center the Text in the Headers for an Ag-Grid Control