简体   繁体   中英

How can I get selected text from webview in android?

I need to get selected text from webview.

For this, I put this:

webView.loadUrl("javascript:Android.getHtml(window.getSelection().toString())");

In my touch event.

  1. touch event works well
  2. Android.getHtml works well (this is javascriptinterface method)
  3. window.getSelection doesn't have any value: it's problem -> in my view, when I touched a word in webview, window.getSelection automatically should contain the text. Am I wrong?

Is there anyone who can have an idea for this?

Very thanks in advance.

Ps: below is my whole code


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_each_news, container, false);

    //설정된 인자값을 받는다
    String newsAddress = getArguments().getString("newsAddress");

    //Start : 받은 주소로 웹뷰를 띄운다...
    webView = (WebView) rootView.findViewById(R.id.webView);
    //  webView.setWebViewClient(new WebViewClient());

    webView.setWebViewClient(new WebViewClient() {});

    webSettings = webView.getSettings();

    webSettings.setJavaScriptEnabled(true);     //자바스크립트 허용여부
    webSettings.setLoadWithOverviewMode(true);  //웹페이지 웹뷰크기에 맞추기 위한 설정
    webSettings.setUseWideViewPort(true);   //웹페이지 웹뷰크기에 맞추기 위한 설정
    webView.setInitialScale(1); //웹페이지 웹뷰크기에 맞추기 위한 설정

    webView.addJavascriptInterface(new MyJavascriptInterface(), "Android"); //자바스크립트 인터페이스 메소드 등록

    //url 호출
    webView.loadUrl(newsAddress);
    webView.setOnTouchListener(this);
    //End : 받은 주소로 웹뷰를 띄운다...

    return rootView;
}

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {

    switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN: {
            //   Toast.makeText(getContext(),"웹뷰클릭",Toast.LENGTH_LONG).show();
            pressStartTime = System.currentTimeMillis();
            pressedX = motionEvent.getX();
            pressedY = motionEvent.getY();
            stayedWithinClickDistance = true;
            break;
        }
        case MotionEvent.ACTION_MOVE: {

            if (stayedWithinClickDistance && getDistance(pressedX, pressedY, motionEvent.getX(), motionEvent.getY()) > MAX_CLICK_DISTANCE) {
                stayedWithinClickDistance = false;
            }
            break;
        }
        case MotionEvent.ACTION_UP: {
            long pressDuration = System.currentTimeMillis() - pressStartTime;
            if (pressDuration < MAX_CLICK_DURATION && stayedWithinClickDistance) {
                // 클릭처리
                webView.evaluateJavascript("(function(){return window.getSelection().toString()})()",
                        new ValueCallback<String>()
                        {
                            @Override
                            public void onReceiveValue(String value)
                            {
                                Log.v(TAG, "SelectedText:" + value);
                            }
                        });
            }
        }
    }
    return false;
}

For API >= 19 you can use evaluateJavascript

mWebview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
    @Override
    public void onReceiveValue(String value)
    {
        Log.v(TAG, "Webview selected text: " + value);
    }
});

For API < 19 you can use evaluateJavascript you use the loadUrl method like below:

mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.addJavascriptInterface(new JavaScriptInterface(), "javascriptinterface");

Then when you want to get the selection use the following:

mWebview.loadUrl("javascript:javascriptinterface.callback(window.getSelection().toString())");

And define a WebAppInterface class as below:

public class JavaScriptInterface
{
    @JavascriptInterface
    public void callback(String value)
    {
        Log.v(TAG, "SELECTION:" + value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM