Injecting JavaScript In WebView Android - javascript

I have the following WebView script :
This script load JavaScript and website url, when the application detect the phrase access_token it should redirect to another webpage with the data from access_token
for example:
the home page loaded
the user visted http://example2.com/?access_token=XXX
the app check the url and redirect user to http://example3.com/?token=XXX
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
String javascriptCodeUrl= "javascript:var token = \n"+
"top.location.href.split('access_token=')[1]; \n"+
"if (token) { \n"+
"top.location.href = 'http://example.com/?user=' + token;}";
mWebView.loadUrl(javascriptCodeUrl);
mWebView.loadUrl("http://default-webpage.com");
// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());
}

You monitor the URLs in shouldOverrideURL method. There is no need to use Javascript injections. It can be done in Java.

Related

webview loads webpage, but some contents get vanished after loading (Android Studio)

I tried to view http://artikelweb.com in a webview. The web page appears nicely. But, whenever I go to any author link from "Popular Authors" section, the web page appears, but, after loading, the quotes aren't showing.
In Google Chrome Browser(mobile) the quotes appear after loading,
but, in my app, the quotes are not showing in web view.
Code Snippet:
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
myWebView = (WebView)findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.artikelweb.com");
myWebView.setWebViewClient(new WebViewClient());
}
#Override
public void onBackPressed() {
if(myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}
In your particular case you must enable the DOM Storage API
webSettings.setDomStorageEnabled(true);
So your code must become:
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
myWebView = (WebView)findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
myWebView.loadUrl("http://www.artikelweb.com");
myWebView.setWebViewClient(new WebViewClient());
}
That becouse the javascript that use the website you are accessing needs it in its javascript.
Of course you could take advantage of a third party library, but again you won't know why this exact case works in the third party one and not in the default webview.
The library you are using has this initial settings:
https://raw.githubusercontent.com/delight-im/Android-AdvancedWebView/master/Source/library/src/main/java/im/delight/android/webview/AdvancedWebView.java
final WebSettings webSettings = getSettings();
webSettings.setAllowFileAccess(false);
setAllowAccessFromFileUrls(webSettings, false);
webSettings.setBuiltInZoomControls(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
if (Build.VERSION.SDK_INT < 18) {
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
}
webSettings.setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < 19) {
webSettings.setDatabasePath(databaseDir);
}
setMixedContentAllowed(webSettings, true);
setThirdPartyCookiesEnabled(true);
Enabling by default many options that the default webview has disable for security reason.
Set UserAgent to your Webview settings and try
webSettings.setUserAgentString("Mozilla/5.0 (Linux; <Android Version>; <Build Tag etc.>) AppleWebKit/<WebKit Rev> (KHTML, like Gecko) Chrome/<Chrome Rev> Mobile Safari/<WebKit Rev>");

Text-to-speech doesn't work in an Android WebView and Firefox

I've got a website (www.myexamplewebsite.com) that looks simplified like this:
<html>
<head>
</head>
<body>
<img src="img/speaker-icon.png" onclick="speakerFunction()">
<script>
function speakerFunction() {
var text = new SpeechSynthesisUtterance("This is a test.");
text.lang = 'en-US';
window.speechSynthesis.speak(text);
}
</script>
</body>
</html>
And I have also a simple Android-application which is basically a webview that displays my website:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.myWebView);
myWebView.loadUrl("www.myexamplewebsite.com");
myWebView.setWebViewClient(new MyWebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
}
// Use when the user clicks a link from a web page in the WebView
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.myexamplewebsite.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
My problem is the following:
When I visit the example website in a normal browser (Chrome, Firefox) on my desktop-pc it works how it should work. If I click on the image on the website, I can hear the text "This is a test."
If I visit the example website with the Chrome-App for Android on my smartphone it works also. But if I visit the website with the Firefox-App or within my own App with the webview (see above) then it doesn't work.
Update 1:
I specified the language explicitely and I tried it with the crosswalk framework but that also didn't solve the problem.
SpeechSynthesisUtterance is not supported by android webview
https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesisUtterance
Although SpeechSynthesis is supported but since SpeechSynthesis work based on the SpeechSynthesisUtterance object passed into it, it won't all still work.
https://developer.mozilla.org/en-US/docs/Web/API/SpeechSynthesis

android webview javascript not working

I am using simple webview.Where i have given link to login page of my web application.
The webview work fine until i try custom webviewClient. By adding webviewClient it stops processing of javascript.I am able to see only html part.
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MyBrowser());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("my web application login page with jscript");
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
I am able to login successfully.There is javascript in login page,so i think it works.But after logging in it redirects to home page where onpage load javascript will append some data to html table.The data which is appended by jscript is visible in other browser,but webview not showing that data.
Try the below that enables javascript
public class WebViewDemo extends Activity {
private static final String URL_TO_LOAD = "http://google.com";
private static final String LOCAL_RESOURCE = "file:///android_asset/html/HelloWorld.html";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.browser_demo);
WebView view= (WebView) findViewById(R.id.browser1);
loadResource(view, LOCAL_RESOURCE);
}
private void loadResource(WebView view, String resource) { wv.loadUrl(resource);
view.getSettings().setJavaScriptEnabled(true);
view.setWebChromeClient(new CustomChromeclient());
view.setWebViewClient(new CustomWebViewclient(this));
view.addJavascriptInterface(new JavaScriptInterface(view), "JSI");
} //

Android - YouTube AdSense does not render on an Android WebView

I have a WebView in Android, and most things render fine. My Youtube videos render fine, but the ads on them do not show up. I checked and JavaScript is enabled. So I am not sure why the ads do not render.
Here is the code that I use:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
webview.getSettings().setAppCacheEnabled(false);
webview.getSettings().setJavaScriptEnabled(true);
webview.setInitialScale(1);
webview.getSettings().setPluginState(PluginState.ON);
WebSettings webSettings = webview.getSettings();
webSettings.setLoadsImagesAutomatically(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setUseWideViewPort(true);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
webview.setWebChromeClient(new WebChromeClient(){});
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setAppCachePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/cache");
webSettings.setDatabaseEnabled(true);
webSettings.setDatabasePath(getApplicationContext().getFilesDir().getAbsolutePath() + "/databases");
webview.loadUrl("http://javatester.org/javascript.html");
}
Would anyone know why the AdSense ads do not render, and how I can make it render?
Thanks!

In Android Webview, am I able to modify a webpage's DOM?

Suppose I load a 3rd party URL through webview.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new MyWebChromeClient());
webview.loadUrl("http://ebay.com");
}
Is it possible for me to inject something into this WebView to replace the ebay logo with my own?
To expand on CommonsWare's correct answer:
WebView webview = new WebView();
webview.setWebViewClient(new WebClient());
webView.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("stackoverflow.com");
then in WebClient:
public class WebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url)
{
// Obvious next step is: document.forms[0].submit()
view.loadUrl("javascript:document.forms[0].q.value='[android]'");
}
}
In a nutshell, you wait for the page to load. Then you loadUrl("javascript:[your javascript here]").
Not directly. You can invoke Javascript code in the context of the current Web page, via loadUrl(), much like a bookmarklet does. However, you do not have direct access to the DOM from Java code.
Since API level 19 there is a handy function evaluateJavascript (String script, ValueCallback<String> resultCallback) that to me makes more sense to use (but I guess the result will be the same). If you just want to run som javascript in the WebView (to modify the DOM for example) the resultCallback can be left empty.
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
webView.evaluateJavascript(
"const images = document.getElementsByTagName(\"img\");\n" +
"for(var i=0; i<images.length; i++){\n" +
" if(images[i].alt == \"eBay Logo\"){\n" +
" images[i].src = \"my_logo.png\";\n" +
" }\n" +
"}", null);
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://ebay.com");
WebView webview = new WebView();
//Maybe need to set to enabled javascript?
webView.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebClient());
webview.loadUrl("stackoverflow.com");

Categories