Background:-
I am attempting to trigger a method called @JavascriptInterface
annotated as processVideo()
from the loadUrl()
function in a webview in order to receive a callback when a user clicks on any video within the webpage.
The solution I have implemented is functioning flawlessly.
@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 Issue:-
When I load my custom JavaScript function in loadUrl()
, I lose the ability to play videos on click. This is expected since I replaced the default behavior with my own code.
My goal is to allow the video to play when clicked, while still receiving the initial callback that was my primary objective.
What I Have Attempted So Far:-
To enable the video playback on click, I utilized:
addEventListener('click',function(){
var video = document.getElementById(jsonData['videoID']);
video.play(); }
This successfully enables video playback.
However, when I combine this solution with my desired callback like so:
addEventListener('click',function(){
Downloader.processVideo(jsonData['src'],jsonData['videoID']);
var video = document.getElementById(jsonData['videoID']);
video.play(); }
I encounter an issue where I do not receive the callback in my processVideo()
.
If I utilize them separately, both functionalities work perfectly within the addEventListener()
, but they do not work simultaneously.