Skip to content

Instantly share code, notes, and snippets.

@albertzak
Created May 23, 2017 12:26
Show Gist options
  • Save albertzak/1f89b617e56ca3e9235d681ff4a2004d to your computer and use it in GitHub Desktop.
Save albertzak/1f89b617e56ca3e9235d681ff4a2004d to your computer and use it in GitHub Desktop.
WebViewDemo
package gq.icctv.webviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
WebView webview = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = ((WebView) findViewById(R.id.webview));
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return false;
}
});
}
public void loadUrl(View button) {
webview.loadUrl("http://google.com");
}
public void loadHtml(View button) {
String summary = "<html>" +
"<body style='background: #BCDFE6; color: #FFF'>" +
"<marquee>" +
"<h1>I'm a web page</h1>" +
"</marquee>" +
"<img width='400' src='https://s-media-cache-ak0.pinimg.com/originals/4f/e1/17/4fe1179802e65971ccaa2e86f592a324.gif'></img>" +
"</body>" +
"</html>";
webview.loadData(summary, "text/html", null);
}
public void injectJS(View button) {
Random generator = new Random();
int randomHue = 60 + generator.nextInt(240);
String js = "" +
"document.body.style.WebkitFilter = 'hue-rotate(" + randomHue + "deg) saturate(3) sepia(0.1)';\n" +
"var field = document.querySelector('.gsfi');\n" +
"field.value = 'Hello from injected JS \uD83E\uDD84';";
webview.evaluateJavascript(js, null);
}
public void injectObject(final View button) {
class Toaster {
@JavascriptInterface
public void toast() {
Toast toast = Toast.makeText(button.getContext(), "Here's your Toast \uD83C\uDF5E", Toast.LENGTH_LONG);
toast.show();
}
}
webview.addJavascriptInterface(new Toaster(), "toaster");
String summary = "<html>" +
"<body>" +
"<button onClick='javascript:toaster.toast()'>" +
"This HTML Button can show a Toast" +
"</button>" +
"</body>" +
"</html>";
webview.loadData(summary, "text/html", null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment