单击链接时,从Android WebView中的锚标记获取href值

Vam*_*lla 12 javascript android webview android-webview

我在WebView中加载一个网页.网页上有一个链接,在桌面上会下载文件,但在应用程序中,链接应显示Toast,表示该应用程序的链接已禁用.

href单击链接时,我不确定如何从锚标记中获取值.

<a class="btn btn-primary" download="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3" href="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3">
<i class="fa fa-download"></i> Download Audio</a>
Run Code Online (Sandbox Code Playgroud)

有人可以分享有关如何执行此操作的想法或任何示例代码.

编辑:1

这是我目前正在做的事情:

private static final String URL = "http://xx.xxx.com/wp-content/uploads/";

webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_DOWN) {

                    WebView.HitTestResult hr = ((WebView) v).getHitTestResult();
                    String extra = hr.getExtra();

                    if (extra != null && extra.startsWith(URL) && extra.endsWith(".mp3")) {
                        Log.d("WebviewActivity", "Extra: " + extra);
                        Log.d("WebviewActivity", "Contains URL");

                        return true;
                    } 
                }

                return false;
            }
        });
Run Code Online (Sandbox Code Playgroud)

这种方法的问题是:当我点击链接时,我得到额外的网址.它工作正常,直到这里.但是,从下一次开始,无论我在哪里点击webview,都会返回相同的额外内容.因此,即使我点击了网址后点击图片,我也会获得相同的网址.不确定我做错了什么.或者这是正确的方法.

如果您需要任何细节,请告诉我.

编辑:2

private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // Get link-URL.
            String url = (String) msg.getData().get("url");

            // Do something with it.
            if (url != null) {
                Log.d(TAG, "URL: "+url);
            }
        }
    };



        webView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_DOWN) {

                    WebView.HitTestResult hr = ((WebView) v).getHitTestResult();


                    if (hr.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {

                        Message msg = mHandler.obtainMessage();
                        webView.requestFocusNodeHref(msg);
                    }


                }

                return false;
            }
        });



        webView.loadUrl(mUrl);

    }
Run Code Online (Sandbox Code Playgroud)

现在,我获取在上一个action_down事件中单击的URL.如何获取当前的URL?

编辑3(尝试使用webviewclient:

 private class MyWebViewClient extends WebViewClient {

        private static final String URL = "xx.xxx.com/wp-content/uploads/";

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            if (!isFinishing())
                mProgressDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mProgressDialog.dismiss();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);

            Toast.makeText(WebviewActivity.this,
                    "Please check your internet " + "connection and try again",
                    Toast.LENGTH_SHORT).show();
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.d("xxx", "Url: " + url);

            if(url.contains(URL)) {
                Log.d("xxx", "Url Contains: " + URL);
                return true;
            }

            return false;
        }

    }


mMyWebViewClient = new MyWebViewClient();
        webView.setWebViewClient(mMyWebViewClient);
Run Code Online (Sandbox Code Playgroud)

单击链接时在logcat中输出:

03-01 15:38:19.402 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:553] focusedNodeChanged: isEditable [false]
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:253] updateKeyboardVisibility: type [0->0], flags [0], show [true], 
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:326] hideKeyboard
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:56] isActive: true
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:65] hideSoftInputFromWindow
Run Code Online (Sandbox Code Playgroud)

Nic*_*oso 7

因为您使用的是 WebView 并且链接不是 Java 脚本,所以使用 WebViewClient 很容易实现,您可以使用它来监视您的 WebView

myWebView.setWebViewClient( new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // check something unique to the urls you want to block
        if (url.contains("xx.xxx.com")) {
            Toast.make... //trigger the toast
            return true; //with return true, the webview wont try rendering the url
        }
        return false; //let other links work normally
    }

} );
Run Code Online (Sandbox Code Playgroud)

有可能因为您的 URL 以 .mp3 结尾,所以文件被视为资源。您还应该覆盖shouldInterceptRequestWebViewClient的方法来检查这一点。

@Override
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { 
    String url = request.getUrl().toString();
    Log.d("XXX", "Url from API21 shouldInterceptRequest : " + url);
    if (url.contains(URL)) { 
        return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>");
    } else {
        return null;
    }
}

public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
    Log.d("XXX", "Url from shouldInterceptRequest : " + url);
    if (url.contains(URL)) { 
        return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>");
    } else {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 0

大部分工作可以在网页端本身完成。您必须编写java脚本来识别哪个设备正在访问该页面(移动设备、桌面设备等)(如果是移动设备),然后使用java脚本绑定技术调用本机android代码来显示Toast消息。

http://developer.android.com/guide/webapps/webview.html

WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
Run Code Online (Sandbox Code Playgroud)

Web应用程序接口.java

public class WebAppInterface {
    Context mContext;

    /** Instantiate the interface and set the context */
    WebAppInterface(Context c) {
        mContext = c;
    }

    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
         Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }
}
Run Code Online (Sandbox Code Playgroud)

YourHTML 页面(此示例单击了按钮)

<input type="button" value="Say hello" onClick="showAndroidToast('Hello  
             Android!')" />

    <script type="text/javascript">
    function showAndroidToast(toast) {
         Android.showToast(toast);
    }
</script>
Run Code Online (Sandbox Code Playgroud)