Is it possible to use Javascript to close Android Browser?

前端 未结 5 755
有刺的猬
有刺的猬 2021-01-21 05:03

I want to put a \"close\" button in a web page (our client wants to do that)
and when I click this button, I want to close Browser (not the current tab but \"browser\" in An

5条回答
  •  [愿得一人]
    2021-01-21 05:39

    Well, a simple work-around for this would be to create an activity with full screen WebView control, display your HTML contents (local or from the Internet) there, and add a button to close this window, with a callback to Java to close this activity. Here is all the code you would need:

    browser.xml layout file:

    
    
        
    
    
    

    myBrowser.java activity (remember to declare it also in AndroidManifest.xml):

    public class myBrowser extends Activity {
        protected WebView webView;
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // if you don't want app title bar...
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.browser);
            webView = (WebView) findViewById(R.id.webkit);
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webView.addJavascriptInterface(new MyJavaCallback(), "JCB");
    
            // get the URL to navigate to, sent in Intent extra
            Intent intent = getIntent();
            if (intent != null) {
                String sUrl = intent.getStringExtra("url");
                if (sUrl != null)
                    webView.loadUrl(sUrl);
            }
        }
    
        final public class MyJavaCallback {
            // this annotation is required in Jelly Bean and later:
            @JavascriptInterface
            public void finishActivity() {
                finish();
            }
        }
    }
    

    The code to start this activity elsewhere in your app would be:

        Intent intent = new Intent(context, myBrowser.class);
        intent.putExtra("url", "http://www.someaddress.com/somepage.html");
        startActivity(intent);
    

    and your somepage.html web page could have a "Close" button with the following code:

    
    

    You may add as well other buttons and callbacks for them to do what's needed in your Android Java code. Calls the other way - from Java to JavaScript on the page, are also possible, e.g.:

    webView.loadUrl("javascript:functionName(params)");
    

    Also, if you want to display content from Internet, not a local file or string in your WebView control, remember to add to AndroidManifest.xml the necessary permission:

    
    

    Greg

提交回复
热议问题