Example usage for android.webkit WebSettings setJavaScriptEnabled

List of usage examples for android.webkit WebSettings setJavaScriptEnabled

Introduction

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

Prototype

public abstract void setJavaScriptEnabled(boolean flag);

Source Link

Document

Tells the WebView to enable JavaScript execution.

Usage

From source file:com.quarterfull.newsAndroid.NewsDetailFragment.java

@SuppressLint("SetJavaScriptEnabled")
private void init_webView() {
    int backgroundColor = ColorHelper.getColorFromAttribute(getContext(), R.attr.news_detail_background_color);
    mWebView.setBackgroundColor(backgroundColor);

    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setJavaScriptCanOpenWindowsAutomatically(false);
    webSettings.setSupportMultipleWindows(false);
    webSettings.setSupportZoom(false);//from   w  w w  .  jav  a 2s .c  om
    webSettings.setAppCacheEnabled(true);

    registerForContextMenu(mWebView);

    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.v(TAG, cm.message() + " at " + cm.sourceId() + ":" + cm.lineNumber());
            return true;
        }

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (progress < 100 && mProgressbarWebView.getVisibility() == ProgressBar.GONE) {
                mProgressbarWebView.setVisibility(ProgressBar.VISIBLE);
            }
            mProgressbarWebView.setProgress(progress);
            if (progress == 100) {
                mProgressbarWebView.setVisibility(ProgressBar.GONE);

                //The following three lines are a workaround for websites which don't use a background color
                int bgColor = ContextCompat.getColor(getContext(),
                        R.color.slider_listview_text_color_dark_theme);
                NewsDetailActivity ndActivity = ((NewsDetailActivity) getActivity());
                mWebView.setBackgroundColor(bgColor);
                ndActivity.mViewPager.setBackgroundColor(bgColor);

                if (ThemeChooser.isDarkTheme(getActivity())) {
                    mWebView.setBackgroundColor(
                            ContextCompat.getColor(getContext(), android.R.color.transparent));
                }
            }
        }
    });

    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (changedUrl) {
                changedUrl = false;

                if (!url.equals("file:///android_asset/") && (urls.isEmpty() || !urls.get(0).equals(url))) {
                    urls.add(0, url);

                    Log.v(TAG, "Page finished (added): " + url);
                }
            }

            super.onPageStarted(view, url, favicon);
        }
    });

    mWebView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (v.getId() == R.id.webview && event.getAction() == MotionEvent.ACTION_DOWN) {
                changedUrl = true;
            }

            return false;
        }
    });
}

From source file:com.mobicage.rogerthat.plugins.messaging.AttachmentViewerActivity.java

@SuppressLint({ "SetJavaScriptEnabled" })
protected void updateView(boolean isUpdate) {
    T.UI();//from w  ww. j  a  v a 2s.c  o  m

    if (!isUpdate && mGenerateThumbnail) {
        File thumbnail = new File(mFile.getAbsolutePath() + ".thumb");
        if (!thumbnail.exists()) {
            boolean isImage = mContentType.toLowerCase(Locale.US).startsWith("image/");
            boolean isVideo = !isImage && mContentType.toLowerCase(Locale.US).startsWith("video/");
            try {
                // Try to generate a thumbnail
                mMessagingPlugin.createAttachmentThumbnail(mFile.getAbsolutePath(), isImage, isVideo);
            } catch (Exception e) {
                L.e("Failed to generate attachment thumbnail", e);
            }
        }
    }

    final String fileOnDisk = "file://" + mFile.getAbsolutePath();

    if (mContentType.toLowerCase(Locale.US).startsWith("video/")) {
        MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(mVideoview);

        Uri video = Uri.parse(fileOnDisk);
        mVideoview.setMediaController(mediacontroller);
        mVideoview.setVideoURI(video);

        mVideoview.requestFocus();
        mVideoview.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mVideoview.start();
            }
        });

        mVideoview.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                L.e("Could not play video, what " + what + ", extra " + extra + ", content_type " + mContentType
                        + ", and url " + mDownloadUrl);

                AlertDialog.Builder builder = new AlertDialog.Builder(AttachmentViewerActivity.this);
                builder.setMessage(R.string.error_please_try_again);
                builder.setCancelable(true);
                builder.setTitle(null);
                builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        dialog.dismiss();
                        finish();
                    }
                });
                builder.setPositiveButton(R.string.rogerthat, new SafeDialogInterfaceOnClickListener() {
                    @Override
                    public void safeOnClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                });
                builder.create().show();
                return true;
            }
        });

    } else if (CONTENT_TYPE_PDF.equalsIgnoreCase(mContentType)) {
        WebSettings settings = mWebview.getSettings();
        settings.setJavaScriptEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowUniversalAccessFromFileURLs(true);
        }

        mWebview.setWebViewClient(new WebViewClient() {

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (fileOnDisk.equals(url)) {
                    return null;
                }
                L.d("404: Expected: '" + fileOnDisk + "'\n Received: '" + url + "'");
                return new WebResourceResponse("text/plain", "UTF-8", null);
            }
        });
        try {
            mWebview.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file="
                    + URLEncoder.encode(fileOnDisk, "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
            L.bug(uee);
        }
    } else {
        WebSettings settings = mWebview.getSettings();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.setAllowFileAccessFromFileURLs(true);
        }
        settings.setBuiltInZoomControls(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);

        if (mContentType.toLowerCase(Locale.US).startsWith("image/")) {
            String html = "<html><head></head><body><img style=\"width: 100%;\" src=\"" + fileOnDisk
                    + "\"></body></html>";
            mWebview.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
        } else {
            mWebview.loadUrl(fileOnDisk);
        }
    }
    L.d("File on disk: " + fileOnDisk);
}

From source file:com.tarun.smartwomen.WebViewDemoActivity.java

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
@Override//from  ww  w .  j  a  va2 s  .  c om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.mainn);

    Intent intent = getIntent();
    reg = intent.getBooleanExtra("reg", false);

    i = (ImageView) findViewById(R.id.hj);

    try {

        big = new GifAnimationDrawable(getResources().openRawResource(R.raw.anim2));
        // big.setOneShot(true);
        android.util.Log.v("GifAnimationDrawable", "===>Four");
    } catch (IOException ioe) {

    }

    i.setImageDrawable(big);
    big.setVisible(true, true);

    sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    // historyStack = new LinkedList<Link>();
    webview = (WebView) findViewById(R.id.webkit);

    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webSettings.setDomStorageEnabled(true);
    // webview.addJavascriptInterface(new WebViewDemoActivity(), "Android");
    // webview.getSettings().setJavaScriptEnabled(true);

    webview.getSettings().setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        // webview.getSettings().setPluginState(PluginState.ON);
        // webview.getSettings().setJavaScriptEnabled(true);
    } else {
        // IMPORTANT!! this method is no longer available since Android 4.3
        // so the code doesn't compile anymore
        // webview.getSettings().setPluginsEnabled(true);
    }

    // Internet

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    connected = false;
    if ((null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) && connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
            || (null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)) {
        // we are connected to a network
        connected = true;
    }

    if (connected == false) {
        /*
         * Toast.makeText(Rss.this,
         * "Connect to internet and Restart Application",
         * Toast.LENGTH_SHORT).show();
         */
        webview.setVisibility(View.INVISIBLE);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WebViewDemoActivity.this);

        // alertDialogBuilder.setTitle("Please connect to Internet");
        alertDialogBuilder.setMessage(
                "In order to provide the freshest recipes and juicing information this app must be connected to the internet, please check your internet settings");
        // set positive button: Yes message

        alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // cancel the alert box and put a Toast to the user

                startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        // show alert
        alertDialog.show();

    }

    // downloads
    // webview.setDownloadListener(new CustomDownloadListener());

    webview.setWebViewClient(new CustomWebViewClient());

    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {

        }

    });

    // http://stackoverflow.com/questions/2083909/android-webview-refusing-user-input
    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }

    });

    if (reg == true) {
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl("http://om-msmartwoman.com/member/register");
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl("http://om-msmartwoman.com/member/register");
        }

        webview.requestFocus();
    } else {
        uhdj = sp.getString("your_int_key", "0");

        Log.e("Url is here ..............................", uhdj);
        // Welcome page loaded from assets directory
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl(uhdj);
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl(uhdj);
        }

        webview.requestFocus();
    }

}

From source file:br.com.bioscada.apps.biotracks.fragments.ChartAndPacerFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.chart_and_pacer, container, false);
    bwebview = (WebView) view.findViewById(R.id.cb_webview1);
    bwebview.setWebViewClient(new MyWebViewClient());
    WebSettings settings = bwebview.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDomStorageEnabled(true);
    openURL();//from  w ww  .j  av a  2  s.  co  m

    zoomControls = (ZoomControls) view.findViewById(R.id.bchart_zoom_controls);
    zoomControls.setOnZoomInClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            zoomIn();
        }
    });

    zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            zoomOut();
        }
    });

    return view;
}

From source file:com.alex.smartwomanmiddleeastfem.WebViewDemoActivity.java

@SuppressLint({ "JavascriptInterface", "SetJavaScriptEnabled" })
@Override/*from  w w  w.java2s. c  o m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.mainn);

    Intent intent = getIntent();
    reg = intent.getBooleanExtra("reg", false);

    i = (ImageView) findViewById(R.id.hj);

    try {

        big = new GifAnimationDrawable(getResources().openRawResource(R.raw.anim2));
        // big.setOneShot(true);
        android.util.Log.v("GifAnimationDrawable", "===>Four");
    } catch (IOException ioe) {

    }

    i.setImageDrawable(big);
    big.setVisible(true, true);

    sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    // historyStack = new LinkedList<Link>();
    webview = (WebView) findViewById(R.id.webkit);

    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);

    webSettings.setDomStorageEnabled(true);
    // webview.addJavascriptInterface(new WebViewDemoActivity(), "Android");
    // webview.getSettings().setJavaScriptEnabled(true);

    webview.getSettings().setBuiltInZoomControls(true);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
        // webview.getSettings().setPluginState(PluginState.ON);
        // webview.getSettings().setJavaScriptEnabled(true);
    } else {
        // IMPORTANT!! this method is no longer available since Android 4.3
        // so the code doesn't compile anymore
        // webview.getSettings().setPluginsEnabled(true);
    }

    // Internet

    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(
            Context.CONNECTIVITY_SERVICE);
    connected = false;
    if ((null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) && connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
            || (null != connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) && connectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED)) {
        // we are connected to a network
        connected = true;
    }

    if (connected == false) {
        /*
         * Toast.makeText(Rss.this,
         * "Connect to internet and Restart Application",
         * Toast.LENGTH_SHORT).show();
         */
        webview.setVisibility(View.INVISIBLE);

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(WebViewDemoActivity.this);

        // alertDialogBuilder.setTitle("Please connect to Internet");
        alertDialogBuilder.setMessage(
                "Through our app offers some offline features, in order to stay actively connected to the SmartWoman community in realtime, you need an internet connection, tap here to check your settings or wait until you have connection.");
        // set positive button: Yes message

        alertDialogBuilder.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // cancel the alert box and put a Toast to the user

                startActivityForResult(new Intent(android.provider.Settings.ACTION_SETTINGS), 0);
            }
        });
        AlertDialog alertDialog = alertDialogBuilder.create();
        // show alert
        alertDialog.show();

    }

    // downloads
    // webview.setDownloadListener(new CustomDownloadListener());

    webview.setWebViewClient(new CustomWebViewClient());

    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int progress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {

        }

    });

    // http://stackoverflow.com/questions/2083909/android-webview-refusing-user-input
    webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!v.hasFocus()) {
                    v.requestFocus();
                }
                break;
            }
            return false;
        }

    });

    if (reg == true) {
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl("http://www.qa-msmartwoman.com/member/register");
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl("http://www.qa-msmartwoman.com/member/register");
        }

        webview.requestFocus();
    } else {
        uhdj = sp.getString("your_int_key", "0");

        //   Log.e("Url is here ..............................", uhdj);
        // Welcome page loaded from assets directory
        if (Locale.getDefault().getLanguage().equals("es")) {

            webview.loadUrl(uhdj);
            // webview.loadUrl("http://live-juice-guru.gotpantheon.com/user/login");
        } else {
            webview.loadUrl(uhdj);
        }

        webview.requestFocus();
    }

}

From source file:com.robandjen.comicsapp.FullscreenActivity.java

@SuppressLint("SetJavaScriptEnabled")
@Override/*  w  ww  . j a v a  2  s  . co m*/
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    setContentView(R.layout.activity_fullscreen);

    final WebView v = (WebView) findViewById(R.id.fullscreen_content);
    v.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            updateShare(url);
            return false;
        }

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

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

    final WebSettings settings = v.getSettings();
    settings.setBuiltInZoomControls(true);
    settings.setJavaScriptEnabled(true);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, R.string.open_drawer,
            R.string.close_drawer);
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);

    if (mComicList == null) {

        try {
            InputStream is = openFileInput(COMICFILE);
            if (!loadXml(is)) {
                Log.w(TAG, "Downloaded list not parseable, defaulting to built-in");
            }
        } catch (FileNotFoundException e) {
            Log.i(TAG, "Downloaded list not found, defaulting to built-in");

        }
    }

    if (mComicList == null) {
        loadDefaultXML();
    }

    if (savedInstanceState != null) {
        mCurComic = savedInstanceState.getInt(CURCOMICKEY, 0);
        final String url = savedInstanceState.getString(CURURLKEY);
        showCurrentComic(url);
    } else {
        do {
            if (!bSkipOther || !mComicList.get(mCurComic).getOther()) {
                break;
            }

            ++mCurComic;
            mCurComic %= mComicList.size();
        } while (mCurComic != 0);
        showCurrentComic();
    }

}

From source file:org.runbuddy.libtomahawk.resolver.ScriptAccount.java

@SuppressLint({ "AddJavascriptInterface", "SetJavaScriptEnabled" })
public ScriptAccount(String path, boolean manuallyInstalled) {
    String prefix = manuallyInstalled ? "file://" : "file:///android_asset";
    mPath = prefix + path;//from   w  ww .j  ava2 s . c  o m
    mManuallyInstalled = manuallyInstalled;
    String[] parts = mPath.split("/");
    mName = parts[parts.length - 1];
    InputStream inputStream = null;
    try {
        if (mManuallyInstalled) {
            File metadataFile = new File(path + File.separator + "content" + File.separator + "metadata.json");
            inputStream = new FileInputStream(metadataFile);
        } else {
            inputStream = TomahawkApp.getContext().getAssets()
                    .open(path.substring(1) + "/content/metadata.json");
        }
        String metadataString = IOUtils.toString(inputStream, Charsets.UTF_8);
        mMetaData = GsonHelper.get().fromJson(metadataString, ScriptResolverMetaData.class);
        if (mMetaData == null) {
            Log.e(TAG, "Couldn't read metadata.json. Cannot instantiate ScriptAccount.");
            return;
        }
    } catch (IOException e) {
        Log.e(TAG, "ScriptAccount: " + e.getClass() + ": " + e.getLocalizedMessage());
        Log.e(TAG, "Couldn't read metadata.json. Cannot instantiate ScriptAccount.");
        return;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                Log.e(TAG, "ScriptAccount: " + e.getClass() + ": " + e.getLocalizedMessage());
            }
        }
    }

    CookieManager.setAcceptFileSchemeCookies(true);

    mWebView = new WebView(TomahawkApp.getContext());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView, true);
    }
    WebSettings settings = mWebView.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setDatabaseEnabled(true);
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        //noinspection deprecation
        settings.setDatabasePath(TomahawkApp.getContext().getDir("databases", Context.MODE_PRIVATE).getPath());
    }
    settings.setDomStorageEnabled(true);
    mWebView.setWebChromeClient(new TomahawkWebChromeClient());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }

    new Handler(Looper.getMainLooper()).post(new Runnable() {
        @Override
        public void run() {
            //initalize WebView
            String data = "<!DOCTYPE html>" + "<html>" + "<head><title>" + mName + "</title></head>" + "<body>"
                    + "<script src=\"file:///android_asset/js/rsvp-latest.min.js"
                    + "\" type=\"text/javascript\"></script>"
                    + "<script src=\"file:///android_asset/js/cryptojs-core.js"
                    + "\" type=\"text/javascript\"></script>";
            if (mMetaData.manifest.scripts != null) {
                for (String scriptPath : mMetaData.manifest.scripts) {
                    data += "<script src=\"" + mPath + "/content/" + scriptPath
                            + "\" type=\"text/javascript\"></script>";
                }
            }
            try {
                String[] cryptoJsScripts = TomahawkApp.getContext().getAssets().list("js/cryptojs");
                for (String scriptPath : cryptoJsScripts) {
                    data += "<script src=\"file:///android_asset/js/cryptojs/" + scriptPath
                            + "\" type=\"text/javascript\"></script>";
                }
            } catch (IOException e) {
                Log.e(TAG, "ScriptResolver: " + e.getClass() + ": " + e.getLocalizedMessage());
            }
            data += "<script src=\"file:///android_asset/js/tomahawk_android_pre.js"
                    + "\" type=\"text/javascript\"></script>"
                    + "<script src=\"file:///android_asset/js/tomahawk.js"
                    + "\" type=\"text/javascript\"></script>"
                    + "<script src=\"file:///android_asset/js/tomahawk-infosystem.js"
                    + "\" type=\"text/javascript\"></script>"
                    + "<script src=\"file:///android_asset/js/tomahawk_android_post.js"
                    + "\" type=\"text/javascript\"></script>" + "<script src=\"" + mPath + "/content/"
                    + mMetaData.manifest.main + "\" type=\"text/javascript\"></script>" + "</body></html>";
            mWebView.setWebViewClient(new ScriptWebViewClient(ScriptAccount.this));
            mWebView.addJavascriptInterface(new ScriptInterface(ScriptAccount.this), SCRIPT_INTERFACE_NAME);
            mWebView.loadDataWithBaseURL("file:///android_asset/test.html", data, "text/html", null, null);
        }
    });
}

From source file:com.chatwingsdk.fragments.CommunicationMessagesFragment.java

private void setupWebView() {
    mWebview.setWebViewClient(new WebViewClient() {
        @Override// w  ww  . j a  v a 2 s.c  o  m
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } catch (Exception e) {
                return false;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //TODO should be when page start rendering chatbox
            LogUtils.v("Loading page DONE");
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            LogUtils.v("Loading page Oh no! " + description);
        }
    });

    mWebview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            LogUtils.v("Loading page " + newProgress + ":" + mWebview);
        }
    });
    WebSettings webSettings = mWebview.getSettings();
    webSettings.setAppCacheEnabled(false);
    webSettings.setJavaScriptEnabled(true);
    mWebview.addJavascriptInterface(mFayeJsInterface, ChatWingJSInterface.CHATWING_JS_NAME);
}

From source file:mobi.monaca.framework.plugin.ChildBrowser.java

/**
 * Display a new browser with the specified URL.
 *
 * @param url           The url to load.
 * @param jsonObject/*  w w  w .j  a  va  2  s .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() {
        /**
         * Convert our DIP units to Pixels
         *
         * @return int
         */
        private int dpToPixels(int dipValue) {
            int value = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, (float) dipValue,
                    cordova.getActivity().getResources().getDisplayMetrics());

            return value;
        }

        public void run() {
            // Let's create the main dialog
            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);
            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");
                    }
                }
            });

            // Main container layout
            LinearLayout main = new LinearLayout(cordova.getActivity());
            main.setOrientation(LinearLayout.VERTICAL);

            // Toolbar layout
            RelativeLayout toolbar = new RelativeLayout(cordova.getActivity());
            toolbar.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, this.dpToPixels(44)));
            toolbar.setPadding(this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2), this.dpToPixels(2));
            toolbar.setHorizontalGravity(Gravity.LEFT);
            toolbar.setVerticalGravity(Gravity.TOP);

            // Action Button Container layout
            RelativeLayout actionButtonContainer = new RelativeLayout(cordova.getActivity());
            actionButtonContainer.setLayoutParams(
                    new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            actionButtonContainer.setHorizontalGravity(Gravity.LEFT);
            actionButtonContainer.setVerticalGravity(Gravity.CENTER_VERTICAL);
            actionButtonContainer.setId(1);

            // Back button
            ImageButton back = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams backLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            backLayoutParams.addRule(RelativeLayout.ALIGN_LEFT);
            back.setLayoutParams(backLayoutParams);
            back.setContentDescription("Back Button");
            back.setId(2);
            back.setImageResource(R.drawable.childbroswer_icon_arrow_left);
            back.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goBack();
                }
            });

            // Forward button
            ImageButton forward = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams forwardLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            forwardLayoutParams.addRule(RelativeLayout.RIGHT_OF, 2);
            forward.setLayoutParams(forwardLayoutParams);
            forward.setContentDescription("Forward Button");
            forward.setId(3);
            forward.setImageResource(R.drawable.childbroswer_icon_arrow_right);
            forward.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    goForward();
                }
            });

            // Edit Text Box
            edittext = new EditText(cordova.getActivity());
            RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
            textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
            textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
            edittext.setLayoutParams(textLayoutParams);
            edittext.setId(4);
            edittext.setSingleLine(true);
            edittext.setText(url);
            edittext.setInputType(InputType.TYPE_TEXT_VARIATION_URI);
            edittext.setImeOptions(EditorInfo.IME_ACTION_GO);
            edittext.setInputType(InputType.TYPE_NULL); // Will not except input... Makes the text NON-EDITABLE
            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;
                }
            });

            // Close button
            ImageButton close = new ImageButton(cordova.getActivity());
            RelativeLayout.LayoutParams closeLayoutParams = new RelativeLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
            closeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            close.setLayoutParams(closeLayoutParams);
            forward.setContentDescription("Close Button");
            close.setId(5);
            close.setImageResource(R.drawable.childbroswer_icon_close);
            close.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    closeDialog();
                }
            });

            // WebView
            webview = new WebView(cordova.getActivity());
            webview.setLayoutParams(
                    new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
            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(6);
            webview.getSettings().setLoadWithOverviewMode(true);
            webview.getSettings().setUseWideViewPort(true);
            webview.requestFocus();
            webview.requestFocusFromTouch();

            // Add the back and forward buttons to our action button container layout
            actionButtonContainer.addView(back);
            actionButtonContainer.addView(forward);

            // Add the views to our toolbar
            toolbar.addView(actionButtonContainer);
            toolbar.addView(edittext);
            toolbar.addView(close);

            // Don't add the toolbar if its been disabled
            if (getShowLocationBar()) {
                // Add our toolbar to our main view/layout
                main.addView(toolbar);
            }

            // Add our webview to our main view/layout
            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 {
            //TODO check LocalFileBootloader
            InputStream input = cordova.getActivity().getAssets().open(filename);
            return BitmapFactory.decodeStream(input);
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
    return "";
}

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

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

        @Override/*from   w w w. j a  va  2s.  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");
        }
    });
}