Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webview - change page source before show website?

I have a website. On the Website, there is a text "Pic". When I show the website in the Webview for the first time I can change the text to "PicGreat". This works!

But, later when a user clicks on a Link (somewhere on the website), then I forward the user to the new HTML Website. Before I show the Website, I want to change the Text "Pic" to "PicGreat".

How can I make that? Should I write a function, and then call the function in "public boolean shouldOverrideUrlLoading"?

I found a similar question here on Stackoverflow, but not solved. how to set webview client

main.xml

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/webview"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
/>

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

WebTest.java

public class WebTestActivity extends Activity {

 WebView mWebView;
 String rline = "";

 /** 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);

 HttpURLConnection urlConnection = null;
 try
 {
 URL url = new URL("http://www.picSite.com/");
 urlConnection = (HttpURLConnection) url.openConnection();
 InputStream in = new BufferedInputStream(urlConnection.getInputStream());
 BufferedReader rd = new BufferedReader(new InputStreamReader(in), 4096);
 String line;

 while ((line = rd.readLine()) != null) {
 rline += line+"\n";
 }
 rd.close();

 } catch (MalformedURLException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 } finally {
 if ( null != urlConnection )
 {
 urlConnection.disconnect();
 }
 }

 String getNewCode = rline.replace("Pic", "PicGreat");

 mWebView.loadData(getNewCode, "text/html", "utf-8");

 mWebView.setWebViewClient(new HelloWebViewClient());
 }

 private class HelloWebViewClient extends WebViewClient {
 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
 view.loadUrl(url);
 return true;
 }

 }
}
like image 617
user1205415 Avatar asked Nov 13 '22 09:11

user1205415


1 Answers

I would use WebViewClient.shouldInterceptRequest():

Notify the host application of a resource request and allow the application to return the data. If the return value is null, the WebView will continue to load the resource as usual. Otherwise, the return response and data will be used.

NOTE: This method is called on a thread other than the UI thread so clients should exercise caution when accessing private data or the view system.

like image 84
Kristian Avatar answered Nov 16 '22 04:11

Kristian