Webview - 在显示网站之前更改页面源?

Posted

技术标签:

【中文标题】Webview - 在显示网站之前更改页面源?【英文标题】:Webview - change page source before show website? 【发布时间】:2012-03-24 07:56:30 【问题描述】:

我有一个网站。在网站上,有一个文字“图片”。当我第一次在 Webview 中显示网站时,我可以将文本更改为“PicGreat”。这行得通!

但是,稍后当用户单击链接(网站上的某处)时,我会将用户转发到新的 html 网站。在展示网站之前,我想将文本“Pic”更改为“PicGreat”。

我怎样才能做到这一点?我应该写一个函数,然后在 “公共布尔应该OverrideUrlLoading”?

我在 *** 上发现了一个类似的问题,但没有解决。 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_
 android:layout_
/>

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;
 

 

【问题讨论】:

【参考方案1】:

我会使用WebViewClient.shouldInterceptRequest():

将资源请求通知主机应用程序并允许 应用程序返回数据。如果返回值为 null,则 WebView 会像往常一样继续加载资源。否则,该 将使用返回响应和数据。

注意:这个方法被调用 UI线程以外的线程,因此客户应谨慎行事 访问私有数据或视图系统时。

【讨论】:

来自 shouldInterceptRequest 的 javadoc,它说它返回一个包含响应信息的 WebResourceResponse 或 null 如果 WebView 应该加载资源本身。我看不出它与重写 html 有什么关系。 @kevin 您可以自己加载页面,重写其源代码并将其返回为WebResourceResponse

以上是关于Webview - 在显示网站之前更改页面源?的主要内容,如果未能解决你的问题,请参考以下文章

没有“允许网站”按钮的 WebView“受限站点”页面

Android WebView:处理方向变化

在android webview应用程序的页面上单击链接时如何防止显示加载微调器?

webview_flutter 无法隐藏/更改某些元素

android system webview是啥

WebView 不显示 KOLIBRI 登录页面