JWPlayer Javascript API for Android Webview - javascript

I'm trying to get JWPlayer to return an alert when a few specific events happen from a flash player playing a local video. If you notice from the code below, onComplete, JWPlayer should return an alert, which can then be intercepted by onJsAlert from setWebChromeClient so I can do stuff with that information. Am I doing something wrong?
A possible reason, I can find here: JWplayer Javascript interaction not working that it's being loaded locally. Is there any way I can bypass this issue? Would it be easier to load somehow by calling localhost? Is that even possible?
For those of you curious about why I generate an HTML file instead of just having one move from the assets - after scouring the Internet to figure out how to get a local flv player working correctly, the best option was to generate the HTML file with the custom information and write the file to the same directory as the FLV (hence the FileWriter function).
HTML code for JWPlayer embed:
private void createVideoHtml(File flvDirectory, File htmlFile, String videofilename)
{
String htmlPre = "<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"utf-8\"></head><body style='margin:0; padding:0;'>";
String htmlCode =
"<script type='text/javascript' src='"+ flvDirectory.getAbsolutePath() + "/jwplayer.js'></script>" +
"<div id='mediaspace'>EZ Stream TV FLV Player</div>" +
"<script type='text/javascript'>" +
"jwplayer('mediaspace').setup({" +
"'flashplayer': '"+ flvDirectory.getAbsolutePath() + "/player.swf', 'file': '" + videofilename + "', 'backcolor': 'FFFFFF', 'frontcolor': '000000', 'lightcolor': '000000'," +
"'screencolor': '000000', 'volume': '100', 'autostart': 'true', 'mute': 'false', 'quality': 'false', 'controlbar': 'bottom', 'width': '100%', 'height': '100%'," +
"events: { " +
"onComplete: function() { alert('COMPLETED');}" +
"}});" +
"</script>";
String htmlPost = "</body></html>";
String finalHTML = htmlPre + htmlCode + htmlPost;
try {
FileWriter f = new FileWriter(htmlFile);
PrintWriter p = new PrintWriter(f);
p.print(finalHTML);
p.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Code for webview and handling the Javscript alert:
webView = (WebView)findViewById(R.id.web_player);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.setInitialScale(60);
webView.setBackgroundColor(Color.BLACK);
getWindow().addFlags(128);
webView.getSettings().setUserAgentString("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result)
{
Log.d(TAG, message);
new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true).show();
result.confirm();
return true;
}
});

You can refer to the code below for JWPlayer to Webview
private void createVideoHtml(File flvDirectory, File htmlFile, String videofilename)
{
String htmlPre = "<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"></head><body style='margin:0; padding:0;'>";
String htmlCode =
"<script type='text/javascript' src='"+ flvDirectory.getAbsolutePath() + "/jwplayer.js'></script>" +
"<div id='mediaspace'>EZ Stream TV FLV Player</div>" +
"<script type='text/javascript'>" +
"jwplayer('mediaspace').setup({" +
"'flashplayer': '"+ flvDirectory.getAbsolutePath() + "/player.swf', 'file': '" + videofilename + "', 'backcolor': 'FFFFFF', 'frontcolor': '000000', 'lightcolor': '000000'," +
"'screencolor': '000000', 'volume': '100', 'autostart': 'true', 'mute': 'false', 'quality': 'false', 'controlbar': 'bottom', 'width': '100%', 'height': '100%'," +
"events: { " +
"onComplete: function() { alert('COMPLETED');}" +
"}});" +
"</script>";
String htmlPost = "</body></html>";
String finalHTML = htmlPre + htmlCode + htmlPost;
try {
FileWriter f = new FileWriter(htmlFile);
PrintWriter p = new PrintWriter(f);
p.print(finalHTML);
p.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
webView = (WebView)findViewById(R.id.web_player);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.setInitialScale(60);
webView.setBackgroundColor(Color.BLACK);
getWindow().addFlags(128);
webView.getSettings().setUserAgentString("Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result)
{
Log.d(TAG, message);
new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true).show();
result.confirm();
return true;
}
});

I had the same problem while working with jwplayer, my conclusion was that the onComplete event isn't trustable in some cases.
Can you benchmark other events does work like the onTime event ?
Otherwise use the onIdle event and measure the time left ( getDuration - getPosition ) to get a custom onComplete event.

Related

Android Javascript interface function not works in ajax callback

I hava webView application in Android. I have defined the javascript interface myapp and I can successfully call it from webpage. I am testing the interface in an ajax function but when I call the functions in ajax success callback, nothing happens:
My Javascript codes in webpage:
function notif(t,v){
try {
myapp.Logit("start"); // I can see this message in Logcat
}catch(err){}
$.ajax({
method:"post",
url:"test.asp",
data:{t:t,v:v},
success:function(data){
alert("done"); // Alert works in webpage
try {
myapp.Logit("finish"); // Nothing happens in Logcat
}catch(err){}
}
})
}
And this is the simple function in Android app to log events in logcat:
#JavascriptInterface
public void Logit(String message){
Log.i("message:",message);
}
How are you injecting the Java object into this WebView?
Please make sure that the you are injecting the Java object into the WebView as below. Without that you won't be able to access the Java objects's method in WebView
webView.addJavascriptInterface(new MyApp(), "MyApp");
It will also help to see if you are getting any error in the debug console. Article on how to setup the remote debugging
below is the sample working code. Hope this helps.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE))
{ WebView.setWebContentsDebuggingEnabled(true); }
}
myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
System.out.println("Web View loaded");
}
});
Button loadBtn = (Button) findViewById(R.id.load_button);
loadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String unencodedHtml =
"<!DOCTYPE html>\n" +
"<html>\n" +
" <head>\n" +
" <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"></script>\n" +
" <script>\n" +
" $(document).ready(function(){\n" +
" $(\"button\").click(function(){\n" +
" $.ajax({\n" +
" method:\"get\",\n" +
" url: \"https://my-json-server.typicode.com/typicode/demo/posts\", \n" +
" success: function(result){\n" +
" alert(\"done\"); \n" +
" try {\n" +
" MyApp.Logit(\"finish\"); // Nothing happens in Logcat\n" +
" }catch(err){}\n" +
" }});\n" +
" });\n" +
" });\n" +
" </script>\n" +
" </head>\n" +
" <body>\n" +
" <button>Get External Content</button>\n" +
" </body>\n" +
"</html>";
String encodedHtml = Base64.encodeToString(unencodedHtml.getBytes(),
Base64.NO_PADDING);
myWebView.loadData(encodedHtml, "text/html", "base64");
}
});
myWebView.addJavascriptInterface(new MyApp(), "MyApp");
}
}
class MyApp
{
#JavascriptInterface
public void Logit(String message){
Log.i("message:",message);
}
}

Using Javascript in android WebView to call a function

Background:-
I am trying to call a #JavascriptInterface annotated method processVideo() form the loadUrl() of webview to get callback when someone click on any video on the webpage.
The following is my approach and it's working perfectly
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
webView = findViewById(R.id.web_view_facebook);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.addJavascriptInterface(this, "Downloader");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onLoadResource(WebView view, String url) {
webView.loadUrl("javascript:(function prepareVideo() { "
+ "var el = document.querySelectorAll('div[data-sigil]');"
+ "for(var i=0;i<el.length; i++)"
+ "{"
+ "var sigil = el[i].dataset.sigil;"
+ "if(sigil.indexOf('inlineVideo') > -1){"
+ "delete el[i].dataset.sigil;"
+ "console.log(i);"
+ "var jsonData = JSON.parse(el[i].dataset.store);"
+ "el[i].addEventListener('click',function(){Downloader.processVideo(jsonData['src'],jsonData['videoID']);});"
+ "}" + "}" + "})()");
}
});
webView.loadUrl("https://m.facebook.com");
}
#JavascriptInterface
public void processVideo(final String vidData, final String vidID) {
try {
Toast.makeText(this, "Download Started", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Download Failed: " + e.toString(), Toast.LENGTH_LONG).show();
}
}}
Now The Problem:-
But as i load custom javascript function in loadUrl(), i lost the ability to play video on click.
i think it will happen as i intercepted and load my custom code
So what i want to achieve is when any user click on video, then the video should play and also i get the callback that i wanted at first place
What i have tried so far:-
to play the video on click, i used
addEventListener('click',function(){
var video = document.getElementById(jsonData['videoID']);
video.play(); }
This one is working perfectly to play the video.
but when i use this solution with my callback like following
addEventListener('click',function(){
Downloader.processVideo(jsonData['src'],jsonData['videoID']);
var video = document.getElementById(jsonData['videoID']);
video.play(); }
then I am not able to get callback in my processVideo().
If i use them individually, both functionality (callback and play video) working perfectly inside addEventListener(), but not working together.
This code line: var video = document.getElementById('jsonData['videoID']') throws an error because you used more than two 's in one argument.
Try replacing by var video = document.getElementById(jsonData['videoID']).
Hope this helps.
I have solved this issue and i am pasting complete code here:
webView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
//query_string = "" + url;
// view.loadUrl("javascript:(function() { document.getElementsByTagName('video')[0].play(); })()");
}
#Override
public void onLoadResource(WebView view, String url)
{
// query_string=""+url;
webView.loadUrl("javascript:(function prepareVideo() " +
"{ "
+ "var el = document.querySelectorAll('div[data-sigil]');"
+"var ID;"
+"var SRC;"
+ "for(var i=0;i<el.length; i++)"
+ "{"
+ "var sigil = el[i].dataset.sigil;"
+ "if(sigil.indexOf('inlineVideo') > -1)" +
"{"
+ "delete el[i].dataset.sigil;"
+ "console.log(i);"
+ "var jsonData = JSON.parse(el[i].dataset.store);"
+"ID=jsonData['videoID'];"
+"SRC=jsonData['src'];"
// +"document.getElementsByTagName(\"'+jsonData['videoID']+'\")[0].play();"
+ "el[i].setAttribute('onClick','FBDownloader.processVideo(\"'+jsonData['src']+'\",\"'+jsonData['videoID']+'\");');"
+ "}"
+ "}"
+ "})()");
}
});
JAVA ACTIVITY FUNCTION WHICH IS CALL FROM JAVASCRIPT WEBVIEW
public void processVideo(final String vidData, final String vidID)
{
this.vidData=vidData;
this.vidID=vidID;
Get_Download_Permission();
showtoast("video ID ="+this.vidID);
webView.loadUrl("https://www.facebook.com/video/embed?video_id="+this.vidID);//193766537709747/");
}

Run JavaScript in Android webview

I've been trying for several hours to run some Javascript in an android webview in which there is html parsed by Jsoup. And despite all my attempts to make it work, I'm still not able to do it.
I've searched all over Google and tried all the answers I found, however none of them did the trick I tried using a method and here's what I ended up with:
Document doc = Jsoup.connect("http://example.com/").get();
Elements web_body = doc.select("body").first().children();
Elements web_head = doc.select("head").first().children();
String javascript = "document.querySelector('h1').innerText='f';"; //Replaces 'Example Domain' with 'f': just an example js code.
WebView webview = findViewById(R.id.webview_id);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
String html_content = "<html>" + "<head>" + web_head.toString() + "</head>" + "<body>" + web_body.toString() + "</body>" + "</html>";
webview.loadDataWithBaseURL("", html_content, "text/html", "UTF-8", "");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
webview.evaluateJavascript(javascript, null);
} else {
webview.loadUrl("javascript:(function(){" + javascript + "})()");
}
The code above shows the example page but javascript doesn't work at all: the app doesn't show any error messages nor crashes.
I'm using a phone with Android O (8.0).
I hope the above information will be useful. I'm still a beginner in Java and any help would be greatly appreciated!
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!

Website Login by using WebView Javascript Android

On Button click:
public void login(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(rlayout.getWindowToken(), 0);
loginWebView.loadUrl("https://example.de");
loginWebView.setVisibility(View.INVISIBLE);
loginWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
loginWebView.loadUrl("javascript: {" +
"document.getElementById('login_act').value = '" + "USNAME" + "';" +
"document.getElementById('login_pwd').value = '" + "PWD" + "';" +
"document.getElementById('submit').click();" +
"};");
}
public void onPageFinished2(WebView view, String url) {
loginWebView.loadUrl(url);
}
});
loginWebView.clearCache(true);
loginWebView.clearHistory();
WebView view = (WebView) this.findViewById(R.id.mainwebView);
String url = "https://example.de";
view.loadUrl(url);
}
On Button click:
1- 1. WebView Login
2- 2. WebView show Page
3- Ready
At my first try all worked. No Error, no problems. The only thing was, that the WebView loaded with the page, where i was not logged in.
How can i log in and what went wrong ?
Try to replace:
public void onPageFinished(WebView view, String url) {
loginWebView.loadUrl("javascript: {" +
"document.getElementById('login_act').value = '" + "USNAME" + "';" +
"document.getElementById('login_pwd').value = '" + "PWD" + "';" +
"document.getElementById('submit').click();" +
"};");
}
With:
public void onPageFinished(WebView view, String url) {
loginWebView.loadUrl("javascript:{" +
"ins=document.getElementsByTagName('input');" +
"ins[0].value='usrn';" +
"ins[1].value='pwd';" +
"ins[2].value=true;" +
"document.getElementsByTagName('form')[0].submit();" +
"};" );
}
Replace for usrn your username and replace for pwd your password. Use ins[2].value=true to hit "remember me". (If there no "remember me" checkbox delete it)
The last entry hit the submit Button.
Main Sourcecode by Jonas w - https://stackoverflow.com/users/5260024/jonas-w
(Just an advanced comment):
"javascript:{
ins=document.getElementsByTagName('input');
ins[0].value='username';
ins[1].value='password';
ins[2].value=true;
document.getElementsByTagName('form')[0].submit();
}"
Das schreibt username ins erste, passwort ins zweite und setzt das Dritte auf true und schickt das erste formular ab...

Open Prezi inside the android app

Anybody knows how to open Prezi Presentation inside the android app or if anyone knows how to add given code in webView please tell me.
What i have tried so for
initializeWebView();
String html, path = "mkg9y_pl1cxd";
html = "<script src=\"http://prezi.github.io/prezi-player/lib/PreziPlayer/prezi_player.js\"></script><div id=\"player-api-intro\"></div> <script> var player = new PreziPlayer('player-api-intro', { 'preziId' : '"
+ path + "', height: '" + screenHeight + "', width: '" + screenWidth
+ "' }); try{ player.on(PreziPlayer.EVENT_STATUS, function(event) { if (event.value == PreziPlayer.STATUS_CONTENT_READY) { var no_of_slides=player.getStepCount(); var user_sec="
+ 10
+ "; var new_sec= user_sec/no_of_slides; setInterval('player.flyToNextStep();', (new_sec * 1000)); } }); }catch(e){} </script></script>";
String mimeType = "text/html";
String encoding = "utf-8";
mainWebView.loadDataWithBaseURL("null",html, mimeType, encoding, "");
private void initializeWebView()
{
String newUA= "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0";
mainWebView = (WebView)findViewById(R.id.Wv);
mainWebView.getSettings().setJavaScriptEnabled(true);
mainWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
mainWebView.getSettings().setDefaultZoom(ZoomDensity.FAR);
mainWebView.getSettings().setAppCachePath( getApplicationContext().getCacheDir().getAbsolutePath() );
mainWebView.getSettings().setAllowFileAccess( true );
mainWebView.getSettings().setAppCacheEnabled( true );
mainWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT );
mainWebView.setVerticalScrollBarEnabled(false);
mainWebView.setHorizontalScrollBarEnabled(false);
mainWebView.setBackgroundColor(0x00000000);
mainWebView.stopLoading();
mainWebView.getSettings().setLoadWithOverviewMode(true);
mainWebView.getSettings().setUseWideViewPort(true);
mainWebView.getSettings().setUserAgentString(newUA);
mainWebView.getSettings().setLoadWithOverviewMode(true);
mainWebView.getSettings().setUseWideViewPort(true);
}
i am getting follwoing error in log cat
11-30 14:12:48.725: E/Web Console(1582): Unsafe JavaScript attempt to access frame with URL null from frame with URL https://prezi.com/player/?oid=mkg9y_pl1cxd&explorable=0&controls=0. Domains, protocols and ports must match.
but i am unable to load presentation in webView. Can anybody tell me what i am doing wrong. Thanks for any help.

Categories

Resources