I am unable to get some javascript to run successfully in the onPageFinished() method of my WebViewClient.
I am porting over an iOS app and they are doing the same thing, waiting for page to load, then using Javascript to hide some of the HTML items.
I don't use Javascript much but am not sure why it keeps failing to work correctly. Right now what happens is the page loads, then onPageFinished is called, and the page reloads and the text 'none' shows up in the top left corner.
I've attached my WebViewClient and then all the WebView setup I am doing in onCreate too. I have also included some commented out code of what I have tried before and that code also did not work.
// Manages the behavior when URLs are loaded
private class Browser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url, headers);
return true;
}
@JavascriptInterface
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//view.loadUrl("javascript:document.getElementById('navbar_bg').style.display = 'none';");
//webView.loadUrl("javascript:document.getElementById(\"content\")");
view.loadUrl("javascript:document.getElementById(\"navbar_bg\").style.display=\"none\";");
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mobile_homework);
ButterKnife.bind(this);
homeworkId = getIntent().getIntExtra(HOMEWORK_ID_EXTRA, 0);
// Configure related browser settings
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
// Enable responsive layout
webView.getSettings().setUseWideViewPort(true);
// Zoom out if the content width is greater than the width of the viewport
webView.getSettings().setLoadWithOverviewMode(true);
//allow manual zoom and get rid of pinch to zoom
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
// Configure the client to use when opening URLs
webView.setWebViewClient(new Browser());
}
Edit: The final fix was to set variables to each change because it returns a variable when you change any item.
Final working code looked like:
view.loadUrl("javascript:var header = document.getElementById('header_bg_first').style.display='none'; " +
"var navbar = document.getElementById('navbar_bg').style.display='none'; " +
"var footer = document.getElementById('footer').style.display='none'; " +
"var iframePadding = document.getElementById('flcn_assignment').style.paddingRight='10px';");