how to get webview content android after loadurl - webview

Here is My Code.
I just want to get the page content from the Webview after load the URL .
On Android, I have a WebView that is displaying a page.
How do I get the page source without requesting the page again?
It seems WebView should have some kind of WebResourceResponse () method in Android 3.0 but don't know how to use it.
public class WebActivity extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://xyz.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
public WebResourceResponse shouldInterceptRequest (WebView view, String url)
{
return null;
}
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
mWebView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}}

I know this is old, but for future visitors, the following should work.
First, you need to define an interface such as:
final class LoadingInterface {
#JavascriptInterface
public void outputHTML(final String html){
//do what ever you want with html
}
}
Then on your WebView call
webView.addJavascriptInterface(new LoadingInterface(), "INTERFACE");
In onPageFinished put:
String js = "javascript:"
+"var html = document.getElementsByTagName('html')[0].innerHTML;"
+"window.INTERFACE.outputSchedule(html);";
webView.loadUrl(js);
If you only need part of a page, you can replace getElementsByTagName('html')[0] with something like getElementById('partOfPage')

Related

How can I set interstitial ads on URL clicks in WebView App?

I have implemented following code for interstitial ads .Problem I am facing is that interstitial ad is shown only on first URL click. I want to adjust ads on every URL click or every 5th URL click in WebView app .Help in this regard will highly be appreciated. Following is the code i want to be modified .
private WebView webview;
private AdView mAdView;
private InterstitialAd mInterstitialAd;
SwipeRefreshLayout mySwipeRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
You need to load Ad after each show. Create a static counter variable to load it on everyth nth click.
static int instanceCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadInterstitial();
}
private void LoadInterstitial(){
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null && isDisplayAdvert()) {
mInterstitialAd.show(MainActivity.this);
LoadInterstitial();
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
private bool isDisplayAdvert(){
instanceCounter++;
if(instanceCounter==5){
instanceCounter = 0;
return true;
}
return false;
}
Thanks sir Amod Gokhale . I tried the following code and it is working too .
Would you recommend me about the better one between both codes .
private class WebViewClientDemo extends WebViewClient {
int n = 1;
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
if( n%6 == 0 )
{
mInterstitialAd.show(MainActivity.this);
} n++;
}
LoadInterstitial();
return super.shouldOverrideUrlLoading(view, url);
}

What happens if user clicks on deep link in the app itself

If I have created a deep link using the branch.io that opens a specific screen in my app. If this link is also available in my app and a user clicks on it, will it open my screen? or it will do nothing as the link I am trying to open from the app is pointing to the same app?
When you click on a Branch link within a webView in your App, you will have to handle the routing to the specific Activity, after reading the Branch link parameters.
Here is a sample Activity which contains a webView and and shows a couple of Branch links. When you click on a link in the webView it reopens the webview and displays the link parameters in a Toast message if a Branch link is clicked
public class MainActivity extends AppCompatActivity {
private WebView webView_;
private Button button_;
private String TAG = "WebViewController";
private Context context_;
private static final String URL_TO_LOAD = "https://evangelosg.github.io/index.html";
private static final String BRANCH_LINK_TO_LOAD = "https://ere6.app.link/b6sS0gsCfG";
#Override
protected void onNewIntent(Intent intent) {
Log.d("WebView", "onNewIntent");
setIntent(intent);
}
#Override
protected void onResume() {
super.onResume();
Branch branch = Branch.getInstance();
branch.initSession(new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if (error == null) {
Log.d(TAG, referringParams.toString());
Toast.makeText(context_, referringParams.toString(), Toast.LENGTH_LONG).show();
if (referringParams.has(BundleExtraKeys.CLICKED_BRANCH_LINK)) {
try {
boolean clickedBranchLink = referringParams.getBoolean(BundleExtraKeys.CLICKED_BRANCH_LINK);
if (clickedBranchLink) {
//do stuff!
}
} catch (JSONException e) {
Log.d("BranchTrends", e.getMessage());
}
}
} else {
Log.i("MyApp", error.getMessage());
}
}
}, this.getIntent().getData(), this);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context_ = this;
setContentView(R.layout.activity_main);
webView_ = (WebView) findViewById(R.id.webView);
webView_.setWebViewClient(new BranchWebViewController("app.link", MainActivity.class));
webView_.loadUrl(URL_TO_LOAD);
button_ = (Button) findViewById(R.id.button);
button_.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.intent.putExtra("branch", BRANCH_LINK_TO_LOAD);
customTabsIntent.intent.putExtra("branch_force_new_session", true);
finish();
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(BRANCH_LINK_TO_LOAD));
}
});
}
public class BranchWebViewController extends WebViewClient {
private String myDomain_;
private Class activityToLaunch_;
BranchWebViewController(#NonNull String myDomain, Class activityToLaunch) {
myDomain_ = myDomain;
activityToLaunch_ = activityToLaunch;
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains(myDomain_)) {
Intent i = new Intent(view.getContext(), activityToLaunch_);
i.putExtra("branch", url);
i.putExtra("branch_force_new_session", true);
finish();
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
}
}
Once you read the link parameters you can route to the appropriate Activity based on the link parameters.

Webview in recyclerview

I have a list of webview to show different pdf's, I need to show it in a horizontal RecyclerView, but the problem is that when I scroll it horizontally then the coming webview just goes on top of the current one and the current one instead of shifting to the left hand side, it remains at its position. It looks a little weird.
This is my RecyclerViewAdapter
public class HorizontalManual extends RecyclerView
.Adapter {
Context context;
private ArrayList<String> list;
public class DataObjectHolder extends RecyclerView.ViewHolder {
ImageView imgUploaded;ProgressBar loader; WebView webViewManual;
public DataObjectHolder(View itemView) {
super(itemView);
webViewManual = (WebView) itemView.findViewById(R.id.pdf_manual_webView);
}
}
public HorizontalManual(Context context, ArrayList<String> list) {
this.context = context;
this.list = list;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = null;
try {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.horz_pdf, parent, false);
if (view.getLayoutParams ().width == RecyclerView.LayoutParams.MATCH_PARENT)
view.getLayoutParams ().width = parent.getWidth ();
} catch (Exception e) {
e.printStackTrace();
}
return new DataObjectHolder(view);
}
#Override
public void onBindViewHolder(final DataObjectHolder holder, final int position) {
String url = "http://docs.google.com/gview?embedded=true&url=" + list.get(position);
Log.e("pdf",url);
WebSettings websettings = holder.webViewManual.getSettings();
websettings.setJavaScriptEnabled(true);
holder.webViewManual.loadUrl(url);
holder.webViewManual.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
holder.webViewManual.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('ndfHFb-c4YZDc-GSQQnc-LgbsSe ndfHFb-c4YZDc-to915-LgbsSe VIpgJd-TzA9Ye-eEGnhe ndfHFb-c4YZDc-LgbsSe')[0].style.display='none'; })()");
}
});
holder.webViewManual.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
holder.webViewManual.setHorizontalScrollBarEnabled(false);
}
#Override
public int getItemCount() {
return list.size();
}
}
I'm setting the HorizontalList in my Fragment like this:
mRecyclerViewManual.setHasFixedSize(true);
rLayoutManagerManual = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false); mRecyclerViewManual.setLayoutManager(rLayoutManagerManual);
//Setting adapter
HorizontalManual setUploadsListAdapterManual = new HorizontalManual(context, list); mRecyclerViewManual.setAdapter(setUploadsListAdapterManual);
Load you google doc url using iframe tag as shown below.
String frameVideo = "<html><body>Youtube video .. <br> <iframe width=\"320\" height=\"315\" src=\"https://docs.google.com/gview?embedded=true&url=http://Dealerapp.ebunch.ca/upload/wl/manuals/7.pdf\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
holder.webView.loadData(frameVideo, "text/html", "utf-8");

Browser filed link click event [duplicate]

I am trying to handle an event in BrowserField when the user actually clicks a link.
I studied BrowserFieldListener, tried its documentCreated() method but that gives me a response when the page starts loading. I want a trigger the moment user clicks a link inside browserField.
What am i missing here?
Override handleNavigationRequest() of ProtocolController like
ProtocolController controller = new ProtocolController(browserField) {
public void handleNavigationRequest(BrowserFieldRequest request) throws Exception {
/*
Here you get the redirection link using
request.getURL()
and do what you want to do
*/
// to display url in browserfield use
InputConnection inputConnection = handleResourceRequest(request);
browserField.displayContent(inputConnection, request.getURL());
}
};
browserField.getConfig().setProperty(BrowserFieldConfig.CONTROLLER, controller);
Use the following class that was I used
public class CacheProtocolController extends ProtocolController{
public CacheProtocolController() {
super(browserField);
}
/**
* Handle navigation requests (e.g., link clicks)
*/
public void handleNavigationRequest(final BrowserFieldRequest request) throws Exception {
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Logger.debug("*******URL*******",request.getURL() );
});
}
/**
* Handle resource request (e.g., images, external css/javascript resources)
*/
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception {
return super.handleResourceRequest(request);
}
}
I have solved this problem using the following class:
public class CacheProtocolController extends ProtocolController{
private SparseList sparseList = null;
private int imageIndex ;
private int click = 0;
private BrowserField browserField = null;
public CacheProtocolController(BrowserField browserField,SparseList sparseList,int imageIndex ) {
super(browserField);
this.sparseList = sparseList;
this.imageIndex = imageIndex;
}
/**
* Handle navigation requests (e.g., link clicks)
*/
public void handleNavigationRequest(final BrowserFieldRequest request) throws Exception {
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
Logger.debug("*******URL*******",request.getURL() );
String requestUrl = null;
requestUrl = FileManipulations.replaceAll(request.getURL(), "file:///SDCard/BlackBerry/pictures/", "../");
Logger.debug("*******requestUrl*******",requestUrl );
Enumeration enumeration = sparseList.elements();
while (enumeration.hasMoreElements()) {
final News news = (News) enumeration.nextElement();
if(news.getDetailsURL().equalsIgnoreCase(requestUrl)){
if(click == 1){
click = 0;
UiApplication.getUiApplication().pushScreen(new DetailedNewsScreen(news.getImageURL() , imageIndex));
} else
click++;
}
}
}
});
}
/**
* Handle resource request (e.g., images, external css/javascript resources)
*/
public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception {
return super.handleResourceRequest(request);
}
}
And in the MainScren use the following
browserField = new BrowserField();
browserField.getConfig().setProperty(BrowserFieldConfig.CONTROLLER, new CacheProtocolController(browserField,List,index));

How to create an URL in Blackberry program

Can anyone tell me how to create an URL link in Blackberry, which opens a web page after it's been clicked?
// This can eb a nested class in your screen class.
class URLButtonField extends ButtonField {
String url;
public URLButtonField(String label, String url) {
super(label);
this.url = url;
}
public String getURL() {
return url;
}
public void setURL(String url) {
this.url = url;
}
}
// member variable of your screen class- this will let you access it later
// to change the URL
URLButtonField bf;
// In your screen's constructor:
bf = new ButtonField("Example", "http://www.example.com");
bf.setFieldChangeListener( new FieldChangeListener() {
void fieldChanged(Field field, int context) {
if (field == this) {
BrowserSession session =- Browser.getDefaultSession();
session.displayPage(getURL());
}
}
} );
add(bf);
You can then change the text or destination URL of "bf" at any time, and whatever you change it to will be the URL that is launched when it is clicked:
// In response to some activity:
bf.setText("Example Two");
bf.setURL("http://www.example.com/two");

Resources