Example usage for android.webkit WebSettings setJavaScriptCanOpenWindowsAutomatically

List of usage examples for android.webkit WebSettings setJavaScriptCanOpenWindowsAutomatically

Introduction

In this page you can find the example usage for android.webkit WebSettings setJavaScriptCanOpenWindowsAutomatically.

Prototype

public abstract void setJavaScriptCanOpenWindowsAutomatically(boolean flag);

Source Link

Document

Tells JavaScript to open windows automatically.

Usage

From source file:org.microg.gms.auth.login.LoginActivity.java

@SuppressLint("SetJavaScriptEnabled")
private static void prepareWebViewSettings(WebSettings settings) {
    settings.setUserAgentString(settings.getUserAgentString() + MAGIC_USER_AGENT);
    settings.setJavaScriptEnabled(true);
    settings.setSupportMultipleWindows(false);
    settings.setSaveFormData(false);/*from  w  ww. j  ava2s.  c  o  m*/
    settings.setAllowFileAccess(false);
    settings.setDatabaseEnabled(false);
    settings.setNeedInitialFocus(false);
    settings.setUseWideViewPort(false);
    settings.setSupportZoom(false);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);
}

From source file:cn.zy.ef.fragment.WebViewFragment.java

protected void configureWebView(WebSettings settings) {
    settings.setJavaScriptCanOpenWindowsAutomatically(true);//js??window.open()false
    settings.setJavaScriptEnabled(true);//??jsfalsetrue????XSS?
    settings.setSupportZoom(true);//??true
    settings.setBuiltInZoomControls(false);//?false
    settings.setUseWideViewPort(true);//???
    settings.setLoadWithOverviewMode(true);//setUseWideViewPort(true)
    settings.setAppCacheEnabled(true);//?
    settings.setDomStorageEnabled(true);//DOM Storage
    settings.setCacheMode(WebSettings.LOAD_DEFAULT);
}

From source file:edu.cscie71.imm.slacker.plugin.Slacker.java

private void openAuthScreen() {
    Runnable runnable = new Runnable() {
        @SuppressLint("NewApi")
        public void run() {
            dialog = new Dialog(cordova.getActivity(), android.R.style.Theme_NoTitleBar);
            dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);//from www  .  j  ava 2 s. c om

            LinearLayout mainLayout = new LinearLayout(cordova.getActivity());
            mainLayout.setOrientation(LinearLayout.VERTICAL);

            inAppWebView = new WebView(cordova.getActivity());
            inAppWebView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT));
            inAppWebView.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new AuthBrowser();
            inAppWebView.setWebViewClient(client);
            WebSettings settings = inAppWebView.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);

            inAppWebView.loadUrl(authURL + "?client_id=" + slackClientID + "&scope=" + scope);
            inAppWebView.getSettings().setLoadWithOverviewMode(true);
            inAppWebView.getSettings().setUseWideViewPort(true);
            inAppWebView.requestFocus();
            inAppWebView.requestFocusFromTouch();

            mainLayout.addView(inAppWebView);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.MATCH_PARENT;
            lp.height = WindowManager.LayoutParams.MATCH_PARENT;

            dialog.setContentView(mainLayout);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

From source file:org.jorge.cmp.ui.fragment.ArticleReaderFragment.java

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    setHasOptionsMenu(Boolean.TRUE);
    final View ret = inflater.inflate(R.layout.fragment_article_reader, container, Boolean.FALSE);
    View mHeaderView = ret.findViewById(R.id.image);
    PicassoUtils.loadInto(mContext, mArticle.getImageUrl(), mDefaultImageId,
            (android.widget.ImageView) mHeaderView, TAG);
    final String title = mArticle.getTitle();
    mHeaderView.setContentDescription(title);
    ((TextView) ret.findViewById(R.id.title)).setText(title);
    WebView contentView = (WebView) ret.findViewById(android.R.id.text1);
    WebSettings webViewSettings = contentView.getSettings();
    contentView.setOverScrollMode(View.OVER_SCROLL_NEVER);
    webViewSettings.setJavaScriptCanOpenWindowsAutomatically(Boolean.TRUE);
    webViewSettings.setBuiltInZoomControls(Boolean.FALSE);
    contentView.setBackgroundColor(0x00000000); //I wonder why the default background is white
    contentView.loadData(mArticle.getPreviewText(), "text/html; charset=UTF-8", "UTF-8");

    mActionBar = mActivity.getSupportActionBar();
    mActionBar.setDisplayHomeAsUpEnabled(Boolean.TRUE);
    mActionBarBackgroundDrawable = new ColorDrawable(
            mContext.getResources().getColor(R.color.toolbar_background));
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        mActionBarBackgroundDrawable.setCallback(mDrawableCallback);
    }/*from  w  w  w .  java2s .  c  o  m*/
    mActionBar.setBackgroundDrawable(mActionBarBackgroundDrawable);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mOriginalElevation = mActionBar.getElevation();
        mActionBar.setElevation(0); //So that the shadow of the ActionBar doesn't show over
        // the article title
    }
    mActionBar.setTitle(mActivity.getString(R.string.section_title_article_reader));

    StickyParallaxNotifyingScrollView scrollView = (StickyParallaxNotifyingScrollView) ret
            .findViewById(R.id.scroll_view);
    scrollView.setOnScrollChangedListener(mOnScrollChangedListener);
    scrollView.smoothScrollTo(0, 0);

    if (!mArticle.isRead()) {
        mMarkAsReadFab = (FloatingActionButton) ret.findViewById(R.id.fab_button_mark_as_read);
        mMarkAsReadFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                markArticleAsRead(mArticle);
                if (mMarkAsReadFab.isShown())
                    mMarkAsReadFab.hide();
            }

            private void markArticleAsRead(FeedArticle article) {
                final Realm r = Realm.getInstanceByRealmId(ArticleReaderFragment.this.mAccount.getRealmEnum());
                String l = PreferenceAssistant.readSharedString(mContext, PreferenceAssistant.PREF_LANG, null);
                if (l == null || !Arrays.asList(r.getLocales()).contains(l)) {
                    l = r.getLocales()[0];
                    PreferenceAssistant.writeSharedString(mContext, PreferenceAssistant.PREF_LANG, l);
                }
                final Class newsClass = NewsListFragment.class;
                final Class communityClass = CommunityListFragment.class;
                final Class schoolClass = SchoolListFragment.class;
                String tableName;
                if (mClass == newsClass) {
                    if (l == null || !Arrays.asList(r.getLocales()).contains(l)) {
                        l = r.getLocales()[0];
                        PreferenceAssistant.writeSharedString(mContext, PreferenceAssistant.PREF_LANG, l);
                    }
                    tableName = SQLiteDAO.getNewsTableName(r, l);
                } else if (mClass == communityClass) {
                    tableName = SQLiteDAO.getCommunityTableName();
                } else if (mClass == schoolClass) {
                    tableName = SQLiteDAO.getSchoolTableName();
                } else {
                    throw new IllegalArgumentException(
                            "Feed list fragment class " + mClass.getCanonicalName() + " not recognized.");
                }
                new AsyncTask<Object, Void, Void>() {
                    @Override
                    protected Void doInBackground(Object... params) {
                        SQLiteDAO.getInstance().markArticleAsRead((FeedArticle) params[0], (String) params[1]);
                        return null;
                    }
                }.executeOnExecutor(Executors.newSingleThreadExecutor(), article, tableName);
                article.markAsRead();
            }
        });

        mMarkAsReadFab.hide();
        mMarkAsReadFab.setVisibility(View.VISIBLE);

        showMarkAsReadFabIfItProceeds();
    }
    return ret;
}

From source file:com.ap.github.ui.activitys.LoginActivity.java

@SuppressLint("SetJavaScriptEnabled")
private void initLoginWebView() {
    mLoginWebView.setVerticalScrollBarEnabled(false);
    mLoginWebView.setHorizontalScrollBarEnabled(false);
    mLoginWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    mLoginWebView.getSettings().setJavaScriptEnabled(true);
    mLoginWebView.setWebViewClient(new LoginWebViewClient(this));

    WebSettings webSettings = mLoginWebView.getSettings();
    webSettings.setUseWideViewPort(true);
    webSettings.setSupportZoom(false);/*from ww  w  .  j a  v a2 s .  c  o  m*/
    webSettings.setBuiltInZoomControls(false);
    webSettings.setAllowFileAccess(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
    webSettings.setLoadsImagesAutomatically(true);
}

From source file:org.openqa.selendroid.server.model.SelendroidWebDriver.java

private void configureWebView(final WebView view) {
    ServerInstrumentation.getInstance().runOnUiThread(new Runnable() {

        @Override//w w  w  .  j  av  a  2  s  .c o  m
        public void run() {
            view.clearCache(true);
            view.clearFormData();
            view.clearHistory();
            view.setFocusable(true);
            view.setFocusableInTouchMode(true);
            view.setNetworkAvailable(true);
            view.setWebChromeClient(new MyWebChromeClient());

            WebSettings settings = view.getSettings();
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setSupportMultipleWindows(true);
            settings.setBuiltInZoomControls(true);
            settings.setJavaScriptEnabled(true);
            settings.setAppCacheEnabled(true);
            settings.setAppCacheMaxSize(10 * 1024 * 1024);
            settings.setAppCachePath("");
            settings.setDatabaseEnabled(true);
            settings.setDomStorageEnabled(true);
            settings.setGeolocationEnabled(true);
            settings.setSaveFormData(false);
            settings.setSavePassword(false);
            settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
            // Flash settings
            settings.setPluginState(WebSettings.PluginState.ON);

            // Geo location settings
            settings.setGeolocationEnabled(true);
            settings.setGeolocationDatabasePath("/data/data/selendroid");
        }
    });
}

From source file:com.wellsandwhistles.android.redditsp.fragments.WebViewFragment.java

@SuppressLint("NewApi")
@Override/*from www  .j a  va2s .  c  o m*/
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    mActivity = (AppCompatActivity) getActivity();

    CookieSyncManager.createInstance(mActivity);

    outer = (FrameLayout) inflater.inflate(R.layout.web_view_fragment, null);

    webView = (WebViewFixed) outer.findViewById(R.id.web_view_fragment_webviewfixed);
    final FrameLayout loadingViewFrame = (FrameLayout) outer
            .findViewById(R.id.web_view_fragment_loadingview_frame);

    /*handle download links show an alert box to load this outside the internal browser*/
    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(final String url, String userAgent, String contentDisposition,
                String mimetype, long contentLength) {
            {
                new AlertDialog.Builder(mActivity).setTitle(R.string.download_link_title)
                        .setMessage(R.string.download_link_message)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent i = new Intent(Intent.ACTION_VIEW);
                                i.setData(Uri.parse(url));
                                getContext().startActivity(i);
                                mActivity.onBackPressed(); //get back from internal browser
                            }
                        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                mActivity.onBackPressed(); //get back from internal browser
                            }
                        }).setIcon(android.R.drawable.ic_dialog_alert).show();
            }
        }
    });
    /*handle download links end*/

    progressView = new ProgressBar(mActivity, null, android.R.attr.progressBarStyleHorizontal);
    loadingViewFrame.addView(progressView);
    loadingViewFrame.setPadding(General.dpToPixels(mActivity, 10), 0, General.dpToPixels(mActivity, 10), 0);

    final WebSettings settings = webView.getSettings();

    settings.setBuiltInZoomControls(true);
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);
    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);
    settings.setDomStorageEnabled(true);
    settings.setDisplayZoomControls(false);

    // TODO handle long clicks

    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, final int newProgress) {

            super.onProgressChanged(view, newProgress);

            General.UI_THREAD_HANDLER.post(new Runnable() {
                @Override
                public void run() {
                    progressView.setProgress(newProgress);
                    progressView.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
                }
            });
        }
    });

    if (mUrl != null) {
        webView.loadUrl(mUrl);
    } else {
        webView.loadDataWithBaseURL("https://reddit.com/", html, "text/html; charset=UTF-8", null, null);
    }

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, final String url) {

            if (url == null)
                return false;

            if (url.startsWith("data:")) {
                // Prevent imgur bug where we're directed to some random data URI
                return true;
            }

            // Go back if loading same page to prevent redirect loops.
            if (goingBack && currentUrl != null && url.equals(currentUrl)) {

                General.quickToast(mActivity,
                        String.format(Locale.US, "Handling redirect loop (level %d)", -lastBackDepthAttempt),
                        Toast.LENGTH_SHORT);

                lastBackDepthAttempt--;

                if (webView.canGoBackOrForward(lastBackDepthAttempt)) {
                    webView.goBackOrForward(lastBackDepthAttempt);
                } else {
                    mActivity.finish();
                }
            } else {

                if (RedditURLParser.parse(Uri.parse(url)) != null) {
                    LinkHandler.onLinkClicked(mActivity, url, false);
                } else {
                    webView.loadUrl(url);
                    currentUrl = url;
                }
            }

            return true;
        }

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

            if (mUrl != null && url != null) {

                final AppCompatActivity activity = mActivity;

                if (activity != null) {
                    activity.setTitle(url);
                }
            }
        }

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

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {

                    General.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {

                            if (currentUrl == null || url == null)
                                return;

                            if (!url.equals(view.getUrl()))
                                return;

                            if (goingBack && url.equals(currentUrl)) {

                                General.quickToast(mActivity, String.format(Locale.US,
                                        "Handling redirect loop (level %d)", -lastBackDepthAttempt));

                                lastBackDepthAttempt--;

                                if (webView.canGoBackOrForward(lastBackDepthAttempt)) {
                                    webView.goBackOrForward(lastBackDepthAttempt);
                                } else {
                                    mActivity.finish();
                                }

                            } else {
                                goingBack = false;
                            }
                        }
                    });
                }
            }, 1000);
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
        }
    });

    final FrameLayout outerFrame = new FrameLayout(mActivity);
    outerFrame.addView(outer);

    return outerFrame;
}

From source file:com.phonegap.plugin.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject /*from w  w w  . ja  va2s .c  o  m*/
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread 
    Runnable runnable = new Runnable() {
        public void run() {
            dialog = new Dialog(ctx.getContext(), android.R.style.Theme_Translucent_NoTitleBar);

            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams forwardParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, 1.0f);
            LinearLayout.LayoutParams closeParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams wvParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT);

            LinearLayout main = new LinearLayout(ctx.getContext());
            main.setOrientation(LinearLayout.VERTICAL);

            LinearLayout toolbar = new LinearLayout(ctx.getContext());
            toolbar.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            toolbar.setOrientation(LinearLayout.HORIZONTAL);

            ImageButton back = new ImageButton(ctx.getContext());
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });
            back.setId(1);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setLayoutParams(backParams);

            ImageButton forward = new ImageButton(ctx.getContext());
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });
            forward.setId(2);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setLayoutParams(forwardParams);

            edittext = new EditText(ctx.getContext());
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });
            edittext.setId(3);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setLayoutParams(editParams);

            ImageButton close = new ImageButton(ctx.getContext());
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });
            close.setId(4);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setLayoutParams(closeParams);

            webview = new WebView(ctx.getContext());
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(5);
            webview.setInitialScale(0);
            webview.setLayoutParams(wvParams);
            webview.requestFocus();
            webview.requestFocusFromTouch();

            toolbar.addView(back);
            toolbar.addView(forward);
            toolbar.addView(edittext);
            toolbar.addView(close);

            if (getShowLocationBar()) {
                main.addView(toolbar);
            }
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = ctx.getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.ctx.runOnUiThread(runnable);
    return "";
}

From source file:com.taobao.wuzhong.plugins.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/*from   w  w w . j av  a 2  s. co  m*/
 */
public String showWebPage(final String url, JSONObject options) {
    // Determine if we should hide the location bar.
    if (options != null) {
        showLocationBar = options.optBoolean("showLocationBar", true);
    }

    // Create dialog in new thread
    Runnable runnable = new Runnable() {
        public void run() {
            dialog = new Dialog(ctx.getContext(), android.R.style.Theme_Translucent_NoTitleBar);

            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(true);
            dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                public void onDismiss(DialogInterface dialog) {
                    try {
                        JSONObject obj = new JSONObject();
                        obj.put("type", CLOSE_EVENT);

                        sendUpdate(obj, false);
                    } catch (JSONException e) {
                        Log.d(LOG_TAG, "Should never happen");
                    }
                }
            });

            LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams forwardParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT, 1.0f);
            LinearLayout.LayoutParams closeParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT);
            LinearLayout.LayoutParams wvParams = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT);

            LinearLayout main = new LinearLayout(ctx.getContext());
            main.setOrientation(LinearLayout.VERTICAL);

            LinearLayout toolbar = new LinearLayout(ctx.getContext());
            toolbar.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            toolbar.setOrientation(LinearLayout.HORIZONTAL);

            ImageButton back = new ImageButton(ctx.getContext());
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });
            back.setId(1);
            try {
                back.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_left.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            back.setLayoutParams(backParams);

            ImageButton forward = new ImageButton(ctx.getContext());
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });
            forward.setId(2);
            try {
                forward.setImageBitmap(loadDrawable("www/childbrowser/icon_arrow_right.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            forward.setLayoutParams(forwardParams);

            edittext = new EditText(ctx.getContext());
            edittext.setOnKeyListener(new View.OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    // If the event is a key-down event on the "enter" button
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        navigate(edittext.getText().toString());
                        return true;
                    }
                    return false;
                }
            });
            edittext.setId(3);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setLayoutParams(editParams);

            ImageButton close = new ImageButton(ctx.getContext());
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });
            close.setId(4);
            try {
                close.setImageBitmap(loadDrawable("www/childbrowser/icon_close.png"));
            } catch (IOException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }
            close.setLayoutParams(closeParams);

            webview = new WebView(ctx.getContext());
            webview.setWebChromeClient(new WebChromeClient());
            WebViewClient client = new ChildBrowserClient(edittext);
            webview.setWebViewClient(client);
            WebSettings settings = webview.getSettings();
            settings.setJavaScriptEnabled(true);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setBuiltInZoomControls(true);
            settings.setPluginsEnabled(true);
            settings.setDomStorageEnabled(true);
            webview.loadUrl(url);
            webview.setId(5);
            webview.setInitialScale(0);
            webview.setLayoutParams(wvParams);
            webview.requestFocus();
            webview.requestFocusFromTouch();

            toolbar.addView(back);
            toolbar.addView(forward);
            toolbar.addView(edittext);
            toolbar.addView(close);

            if (getShowLocationBar()) {
                main.addView(toolbar);
            }
            main.addView(webview);

            WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(dialog.getWindow().getAttributes());
            lp.width = WindowManager.LayoutParams.FILL_PARENT;
            lp.height = WindowManager.LayoutParams.FILL_PARENT;

            dialog.setContentView(main);
            dialog.show();
            dialog.getWindow().setAttributes(lp);
        }

        private Bitmap loadDrawable(String filename) throws java.io.IOException {
            InputStream input = ctx.getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.ctx.runOnUiThread(runnable);
    return "";
}

From source file:com.wpi.assistments.HomeTabbedActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_webview);

    final ProgressDialog pd = ProgressDialog.show(this, "", "Loading...", true);

    isTeacher = false;//from  w ww. j a v a2  s  .  c  o  m
    toggle = true;
    logoutFlag = false;

    homeWebView = (WebView) findViewById(R.id.homeWebView);
    homeWebView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            Log.i("test", view.getUrl());
            if (view.getUrl().equals("https://www.assistments.org/account/login") && !logoutFlag) {

                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                intent.putExtra("showPopup", "true");
                startActivity(intent);
                finish();
            } else if (view.getUrl().equals("https://www.assistments.org/teacher")) {
                isTeacher = true;
            } else if (view.getUrl().equals("https://www.assistments.org/account/login") && logoutFlag) {
                Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
            }

            if (!homeWebView.canGoBack()) {
                btnBack.setEnabled(false);
            } else {
                btnBack.setEnabled(true);
            }

            if (!homeWebView.canGoForward()) {
                btnForward.setEnabled(false);
            } else {
                btnForward.setEnabled(true);
            }

            if (pd.isShowing() && pd != null) {
                pd.dismiss();
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            pd.show();
            view.loadUrl(url);
            return true;
        }
    });
    homeWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
            new AlertDialog.Builder(webviewContext).setTitle("ASSISTments").setMessage(message)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            logoutFlag = true;
                            result.confirm();
                        }
                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            result.cancel();
                        }
                    }).create().show();

            return true;
        }
    });

    if (savedInstanceState != null) {
        homeWebView.restoreState(savedInstanceState);
    } else {
        /** Scaling, replaced by overview mode and wide view port
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        if (size.x <= 780) {
           int scaleRate = (int) ((size.x) / 7.8);
           Log.i("test", Integer.toString(size.x));
           homeWebView.setInitialScale(scaleRate);
        }
        */

        Intent intent = getIntent();

        if (intent.getStringExtra("username").equals("") && intent.getStringExtra("password").equals("")) {
            homeWebView.loadUrl("https://www.assistments.org/signup");

        } else {
            String username = intent.getStringExtra("username");
            String password = intent.getStringExtra("password");

            String postData = "login=" + username + "&password=" + password + "&commit=Log in";
            homeWebView.postUrl("https://www.assistments.org/account/login",
                    EncodingUtils.getBytes(postData, "BASE64"));
        }

    }

    WebSettings settings = homeWebView.getSettings();
    settings.setSaveFormData(false);
    settings.setSavePassword(false);
    settings.setJavaScriptEnabled(true);
    settings.setBuiltInZoomControls(true);
    settings.setDisplayZoomControls(false);
    settings.setJavaScriptCanOpenWindowsAutomatically(true);
    settings.setSupportMultipleWindows(true);
    settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
    settings.setAppCacheEnabled(false);
    settings.setDomStorageEnabled(true);
    settings.setDatabaseEnabled(true);
    settings.setUseWideViewPort(false);
    settings.setLoadWithOverviewMode(true);
    homeWebView.clearCache(true);
    homeWebView.setPadding(0, 0, 0, 0);
    homeWebView.setInitialScale(getScale());

    btnBack = (Button) findViewById(R.id.btnBack);
    btnBack.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            homeWebView.goBack();
        }
    });

    btnRefresh = (Button) findViewById(R.id.btnRefresh);
    btnRefresh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            //homeWebView.zoomOut();
            homeWebView.scrollTo(1000, 0);
            Log.i("test", "111");
            //homeWebView.reload();
        }
    });

    btnForward = (Button) findViewById(R.id.btnForward);
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            homeWebView.goForward();
        }
    });

    btnOffline = (Button) findViewById(R.id.btnOffline);
    btnOffline.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (toggle) {
                homeWebView.loadUrl(
                        "https://www.assistments.org/assistments/student/index.html#offlineUserAssignmentList/");
                btnOffline.setText("Home");
                toggle = false;
            } else {
                if (isTeacher) {
                    homeWebView.loadUrl("https://www.assistments.org/teacher");
                } else {
                    homeWebView.loadUrl("https://www.assistments.org/tutor");
                }
                btnOffline.setText("Offline");
                toggle = true;
            }

        }
    });
}