如何获取webView上的部分内容

如何获取webView上的部分内容,第1张

The extensive Android SDK allows you to do many great things with particular views like the WebView for displaying webpages on Android powered devices

Android SDK 的扩展通过使用特定的view允许你做许多事情比如WebView用来在Android手机上展示网页

As of lately while I was experimenting with the Android SDK I was using a WebView in one of my activities

最近我在体验Android SDK的时候在一个Activity中用到了WebView

From that particular WebView I needed to know the ContentHeight but also the ContentWidth

从WebView我不但想要知道ContentHeight还想知道ContentWidth

Now getting the contentHeight is easy like so:

现在的情况是获取contentHeight很easy如下

webviewgetContentHeight();

Unfortunately getting the contentWidth from a WebView is rather more difficult since there is not a simple method like:

不幸的是从一个WebView获取contentWidth是相当困难因为SDK中没有一个像这样的方法

// THIS METHOD DOES NOT EXIST!

webviewgetContentWidth();

There are ways to get the contentWidth of the rendered HTML page and that is through Javascript If Javascript can get it for you then you can also have them in your Java code within your Android App

当然是有方法获取contentWidth的就是通过Javascript来获取如果你能够支持Javascript那么你就可以在你的Android 程序中使用java代码来获取宽度

By using a JavascriptInterface with your WebView you can let Javascript communicate with your Android App Java code by invoking methods on a registered object that you can embed using the JavascriptInterface

通过在你的WebView中使用JavascriptInterface通过调用你注册的JavascriptInterface方法可以让Javascript和你的Android程序的java代码相互连通

So how does this work

怎么做呢?

For a quick example I created a simple Activity displaying a webview that loads a webpage wich displays a log message and a Toast message with the contentWidth wich was determined using Javascript Note that this happens AFTER the page was finished loading because before the page is finished loading the width might not be fully rendered Also keep in mind that if there is content loaded asynchronously that it doesnt affect widths (most likely only heights will be affected as the width is almost always fully declared in CSS files unless you have a % width webpage)

搭建一个快速的例子创建一个简单的展示webView的Activity一个LogCat消息一个Toast消息用来显示我们通过 Javascript获取的宽度注意这些会在网页完全加载之后显示因为在网页加载完成之前宽度可能不能够正确的获取到同时也要注意到如果是异 步加载这并不影响宽度(最多高度会受影响因为宽度总是在CSS文件中做了完全的定义除非在网页中你用了%宽度)

Below is the code of the Activity Mainjava:

下面的代码是Activity的代码

package compimmosandroidsampleswebviewcontentwidth;

import androidappActivity;

import androidosBundle;

import androidutilLog;

import androidwebkitWebView;

import androidwebkitWebViewClient;

import androidwidgetToast;

publicclass Main extends Activity {

privatefinalstatic String LOG_TAG = "WebViewContentWidth";

privatefinal Activity activity = this;

privatestaticint webviewContentWidth = ;

privatestatic WebView webview;

/ Called when the activity is first created /

@Override

publicvoid onCreate(Bundle savedInstanceState) {

superonCreate(savedInstanceState);

setContentView(Rlayoutmain);

webview = (WebView) findViewById(Ridwebview);

webviewgetSettings()setJavaScriptEnabled(true);

webviewsetSaveEnabled(true);

webviewaddJavascriptInterface(new JavaScriptInterface() "HTMLOUT");

webviewsetWebViewClient(new WebViewClient() {

@Override

publicvoid onPageFinished(WebView view String url) {

webviewloadUrl("javascript:windowHTMLOUTgetContentWidth(documentgetElementsByTagName(html)[]scrollWidth);");

}

});

webviewloadUrl(";);

}

class JavaScriptInterface {

publicvoid getContentWidth(String value) {

if (value != null) {

webviewContentWidth = IntegerparseInt(value);

Logd(LOG_TAG "Result from javascript: " + webviewContentWidth);

ToastmakeText( activity

"ContentWidth of webpage is: " +

webviewContentWidth +

"px" ToastLENGTH_SHORT)show();

}

}

}

}

Below is the XML layout used with the Activity wich only contains a simple WebView:

下面是Activity的Layout主要就是一个简单的WebView

<xml version="" encoding="utf">

<LinearLayout

xmlns:android=";

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent">

<WebView android:id="@+id/webview"

android:layout_width="fill_parent"

android:layout_height="fill_parent" />

</LinearLayout>

AndroidManifestxml layout:

AndroidManifestxml代码

<xml version="" encoding="utf">

<manifest

xmlns:android=";

package="compimmosandroidsampleswebviewcontentwidth"

android:versionCode="" android:versionName="">

<application android:icon="@drawable/icon"

android:label="@string/app_name">

<activity android:name="Main"

android:label="@string/app_name">

<intentfilter>

<action android:name="androidintentactionMAIN" />

<category

android:name="androidintentcategoryLAUNCHER" />

</intentfilter>

</activity>

</application>

<usessdk android:minSdkVersion="" />

<usespermission android:name="androidpermissionINTERNET" />

</manifest>

You can also download the full source of Android Application WebViewContentWidth!

webview 获取 网页的title

WebView mWebView = (WebView) findViewById(Ridmwebview);

mWebViewsetWebViewClient(new WebViewClient() {

@Override

public void onPageFinished(WebView view, String url) {

ExperimentingActivitythissetTitle(viewgetTitle());

}

});

getTitle

public String getTitle()

Get the title for the current page This is the title of the current page until WebViewClientonReceivedTitle is called

返回:

The title for the current page

下面这篇文章总结的比较全 ,但是 onReceivedTitle()方法在goback()之后无效。

如有转载,请声明出处: 时之沙: >

webview js之间的交互,项目中马上用到。

JS调用java代码效果图

java代码调用javasrcipt代码效果图

indexhtml代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 401//EN" ">

<xml version="10" encoding="utf-8"><LinearLayout xmlns:android=">

public class MainActivity extends AppCompatActivity {private WebView mWebView;    @Override    protected void onCreate(Bundle savedInstanceState) {        superonCreate(savedInstanceState);        setContentView(Rlayoutactivity_main);         mWebView = (WebView) findViewById(Ridtest_webview);        //设置WebView支持JavaScript        mWebViewgetSettings()setJavaScriptEnabled(true);        mWebViewloadUrl("file:///android_asset/indexhtml");        mWebViewaddJavascriptInterface(new JsInterface(this), "AndroidWebView");        //添加客户端支持        mWebViewsetWebChromeClient(new WebChromeClient());        findViewById(Ridtest_btn)setOnClickListener(new ViewOnClickListener() {            @Override            public void onClick(View v) {

sendInfoToJs();            }

});    }    private class JsInterface {        private Context mContext;        public JsInterface(Context context) {            thismContext = context;        }        //在js中调用windowAndroidWebViewshowInfoFromJs(name),便会触发此方法。        @JavascriptInterface        public void showInfoFromJs(String share) {

ToastmakeText(mContext, share, ToastLENGTH_SHORT)show();        }

}    //在java中调用js代码    public void sendInfoToJs() {

String msg = ((EditText)findViewById(Ridtest_edt))getText()toString();        //调用js中的函数:showInfoFromJava(msg)        mWebViewloadUrl("javascript:showInfoFromJava('" + msg + "')");    }

总结下,java代码中要设置webview对javascript的支持,addJavascriptInterface(new JsInterface(this), "AndroidWebView");//这句代码中的第二个参数是在js访问方法的地址。

windowAndroidWebViewshowInfoFromJs(share);

webView获取网页标签值

HTML DOM使用

获取html标签值:

方法1:

方法2: 不使用loadUrl()方法,也无需添加js接口回调

两种方法的输出结果:

注意: 其中使用documentgetElementsByTagName('span')[0]innerHTML也能获取到标签的值。

但是根据class获取documentgetElementsByClassName("data2")innerHTML无法获取到标签值,Id也是一样。不过使用documentquerySelector('spandata2')方法无论是标签,class,id都能获取到。

以上就是关于如何获取webView上的部分内容全部的内容,包括:如何获取webView上的部分内容、webview中有没有办法获取到网页源代码,加载AJAX后的、Android 在WebView中通过javascript获取网页源码,并在TextView或者在EditText中显示问题等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/9423182.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-28
下一篇 2023-04-28

发表评论

登录后才能评论

评论列表(0条)

保存