setJavaScriptCanOpenWindowsAuto的真正目的是什么?

时间:2016-07-28 05:28:34

标签: javascript android webview

根据Android document

  

告诉JavaScript自动打开窗口。这适用于JavaScript函数window.open()。默认值为false。

但我没有看到使用或不使用此API在我的代码中有任何不同,window.open在这两种情况下都能正常工作,那么这个API的真正目的是什么或我的用法不正确?

我的代码示例如下:

public class MainActivity extends Activity {
private WebView mWebView;
//private Context mContext
RelativeLayout mParent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mParent = new RelativeLayout(MainActivity.this);
    setContentView(mParent);

    mWebView = new WebView(MainActivity.this);
    WebSettings settings = mWebView.getSettings();
    settings.setSupportMultipleWindows(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);
    settings.setJavaScriptEnabled(true);
    mParent.addView(mWebView);
    mWebView.loadUrl("file:///android_asset/create_window.html");

    mWebView.setWebViewClient(new MyWebViewClient());
    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, Message resultMsg) {
            WebView newWebView = new WebView(view.getContext());
            newWebView.getSettings().setUserAgentString("BBB");
            //newWebView.getSettings().setJavaScriptEnabled(true);
            //newWebView.setWebChromeClient(this);
            newWebView.setWebViewClient(new MyWebViewClient());
            //view.getSettings().setUserAgentString("CCC");
            mParent.addView(newWebView);
            WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();
            return true;
        }

        @Override
        public void onCloseWindow(WebView window) {
            mParent.removeViewAt(mParent.getChildCount() - 1);
        }
    });

}

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

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

    }

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

    }
}

}

create_window.html的内容如下:

<html>
<!-- scripts -->
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Create Window</title>
    <script>
        function
        openURL ()
        {
            alert ("opening window");
            window.open ("http://www.whoishostingthis.com/tools/user-agent/",  "_blank", "width=200,height=100");
        }
    </script>
</head>

<body>
<div>
  <button onclick="openURL()">open website in new window</button>
</div>
</body>

</html>

0 个答案:

没有答案