Search in sources :

Example 31 with WebResourceRequest

use of android.webkit.WebResourceRequest in project mintube by imshyam.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    mainAct = this;
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    viewStub = (ViewStub) findViewById(R.id.view_stub);
    if (isInternetAvailable(mainAct)) {
        viewStub.setLayoutResource(R.layout.content_main);
        viewStub.inflate();
        exit = false;
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Swipe Refresh WebView
        swipeRefreshLayout = (CustomSwipeRefresh) findViewById(R.id.swipe_refresh);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

            @Override
            public void onRefresh() {
                swipeRefreshLayout.setRefreshing(true);
                new Handler().post(new Runnable() {

                    @Override
                    public void run() {
                        youtubeView.loadUrl(youtubeView.getUrl());
                    }
                });
            }
        });
        // after initialization
        swipeRefreshLayout.setCanChildScrollUpCallback(new CustomSwipeRefresh.CanChildScrollUpCallback() {

            @Override
            public boolean canSwipeRefreshChildScrollUp() {
                return youtubeView.getScrollY() > 0;
            }
        });
        youtubeView = (WebView) findViewById(R.id.youtube_view);
        youtubeView.getSettings().setJavaScriptEnabled(true);
        youtubeView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageStarted(WebView view, String str, Bitmap bitmap) {
                super.onPageStarted(view, str, bitmap);
                Log.d("Main Page Loading ", str);
                swipeRefreshLayout.setRefreshing(true);
                currUrl = str;
            }

            @Override
            public void onPageFinished(WebView view, String str) {
                super.onPageFinished(view, str);
                swipeRefreshLayout.setRefreshing(false);
                Log.d("Main Page Finished", str);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.contains("?app=desktop") && !url.contains("signin?app=desktop")) {
                    Log.d("Url stopped to load : ", url);
                    CoordinatorLayout coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinator_layout);
                    final Snackbar snackbar = Snackbar.make(coordinatorLayout, "Desktop View Unavailable", Snackbar.LENGTH_LONG);
                    // Changing Text Color
                    View snkBar = snackbar.getView();
                    TextView tv = (TextView) snkBar.findViewById(android.support.design.R.id.snackbar_text);
                    tv.setTextColor(Color.parseColor("#e52d27"));
                    snackbar.show();
                    return true;
                }
                return false;
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    if (String.valueOf(request.getUrl()).contains("http://m.youtube.com/watch?") || String.valueOf(request.getUrl()).contains("https://m.youtube.com/watch?")) {
                        String url = String.valueOf(request.getUrl());
                        Log.d("Yay Catches!!!! ", url);
                        // Video Id
                        VID = url.substring(url.indexOf("&v=") + 3, url.length());
                        Log.d("VID ", VID);
                        // Playlist Id
                        final String listID = url.substring(url.indexOf("&list=") + 6, url.length());
                        Pattern pattern = Pattern.compile("([A-Za-z0-9_-]+)&[\\w]+=.*", Pattern.CASE_INSENSITIVE);
                        Matcher matcher = pattern.matcher(listID.toString());
                        Log.d("ListID", listID);
                        PID = "";
                        if (matcher.matches()) {
                            PID = matcher.group(1);
                        }
                        if (listID.contains("m.youtube.com")) {
                            Log.d("Not a ", "Playlist.");
                            PID = null;
                        } else {
                            Constants.linkType = 1;
                            Log.d("PlaylistID ", PID);
                        }
                        Handler handler = new Handler(getMainLooper());
                        final String finalPID = PID;
                        handler.post(new Runnable() {

                            @Override
                            public void run() {
                                youtubeView.stopLoading();
                                youtubeView.goBack();
                                if (isServiceRunning(PlayerService.class)) {
                                    Log.d("Service : ", "Already Running!");
                                    PlayerService.startVid(VID, finalPID);
                                } else {
                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(MainActivity.this)) {
                                        Intent i = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                                        startActivityForResult(i, OVERLAY_PERMISSION_REQ);
                                    } else {
                                        Intent i = new Intent(MainActivity.this, PlayerService.class);
                                        i.putExtra("VID_ID", VID);
                                        i.putExtra("PLAYLIST_ID", finalPID);
                                        i.setAction(Constants.ACTION.STARTFOREGROUND_WEB_ACTION);
                                        startService(i);
                                    }
                                // Intent i = new Intent(MainActivity.this, PlayerService.class);
                                // i.putExtra("VID_ID", VID);
                                // i.putExtra("PLAYLIST_ID", finalPID);
                                // i.setAction(Constants.ACTION.STARTFOREGROUND_WEB_ACTION);
                                // startService(i);
                                }
                            }
                        });
                    }
                }
                return super.shouldInterceptRequest(view, request);
            }
        });
        youtubeView.canGoBack();
        currUrl = "https://m.youtube.com/";
        youtubeView.loadUrl(currUrl);
    } else {
        viewStub.setLayoutResource(R.layout.content_main_no_internet);
        viewStub.inflate();
        exit = true;
        retry = (Button) findViewById(R.id.retry_internet);
        changeSettings = (Button) findViewById(R.id.change_settings);
        exitApp = (Button) findViewById(R.id.exit_app);
        retry.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mainAct.recreate();
            }
        });
        changeSettings.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(Settings.ACTION_SETTINGS), 0);
            }
        });
        exitApp.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}
Also used : Pattern(java.util.regex.Pattern) CustomSwipeRefresh(com.shapps.mintubeapp.CustomViews.CustomSwipeRefresh) WebResourceRequest(android.webkit.WebResourceRequest) Matcher(java.util.regex.Matcher) Handler(android.os.Handler) Intent(android.content.Intent) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) SearchView(android.support.v7.widget.SearchView) ImageView(android.widget.ImageView) View(android.view.View) WebView(android.webkit.WebView) TextView(android.widget.TextView) CoordinatorLayout(android.support.design.widget.CoordinatorLayout) Bitmap(android.graphics.Bitmap) WebResourceResponse(android.webkit.WebResourceResponse) TextView(android.widget.TextView) WebView(android.webkit.WebView) Toolbar(android.support.v7.widget.Toolbar) WebViewClient(android.webkit.WebViewClient) Snackbar(android.support.design.widget.Snackbar)

Example 32 with WebResourceRequest

use of android.webkit.WebResourceRequest in project MaterialFBook by ZeeRooo.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    Theme.Temas(this, mPreferences);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = findViewById(R.id.webview);
    mNavigationView = findViewById(R.id.nav_view);
    mNavigationView.setNavigationItemSelectedListener(this);
    drawer = findViewById(R.id.drawer_layout);
    // Setup the toolbar
    Toolbar mToolbar = findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    searchToolbar();
    // Setup the DrawLayout
    final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    URLs();
    switch(mPreferences.getString("start_url", "Most_recent")) {
        case "Most_recent":
            mWebView.loadUrl(baseURL + "home.php?sk=h_chr");
            break;
        case "Top_stories":
            mWebView.loadUrl(baseURL + "home.php?sk=h_nor");
            break;
        case "Messages":
            mWebView.loadUrl(baseURL + "messages/");
            break;
        default:
            break;
    }
    DBHelper = new DatabaseHelper(this);
    bookmarks = new ArrayList<>();
    final Cursor data = DBHelper.getListContents();
    while (data.moveToNext()) {
        if (data.getString(1) != null && data.getString(2) != null) {
            bk = new BookmarksH(data.getString(1), data.getString(2));
            bookmarks.add(bk);
        }
    }
    BLAdapter = new BookmarksAdapter(this, bookmarks, DBHelper);
    BookmarksListView = findViewById(R.id.bookmarksListView);
    BookmarksListView.setAdapter(BLAdapter);
    BookmarksListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView adapter, View view, int position, long arg) {
            BookmarksH item = (BookmarksH) BookmarksListView.getAdapter().getItem(position);
            mWebView.loadUrl(item.getUrl());
            drawer.closeDrawers();
        }
    });
    ImageButton newbookmark = findViewById(R.id.add_bookmark);
    newbookmark.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            bk = new BookmarksH(mWebView.getTitle(), mWebView.getUrl());
            DBHelper.addData(bk.getTitle(), bk.getUrl(), null);
            bookmarks.add(bk);
            BLAdapter.notifyDataSetChanged();
            CookingAToast.cooking(MainActivity.this, getString(R.string.new_bookmark) + " " + mWebView.getTitle(), Color.WHITE, Color.parseColor("#214594"), R.drawable.ic_bookmarks, false).show();
        }
    });
    mr_badge = (TextView) mNavigationView.getMenu().findItem(R.id.nav_most_recent).getActionView();
    fr_badge = (TextView) mNavigationView.getMenu().findItem(R.id.nav_friendreq).getActionView();
    // Hide buttons if they are disabled
    if (!mPreferences.getBoolean("nav_groups", false))
        mNavigationView.getMenu().findItem(R.id.nav_groups).setVisible(false);
    if (!mPreferences.getBoolean("nav_search", false))
        mNavigationView.getMenu().findItem(R.id.nav_search).setVisible(false);
    if (!mPreferences.getBoolean("nav_mainmenu", false))
        mNavigationView.getMenu().findItem(R.id.nav_mainmenu).setVisible(false);
    if (!mPreferences.getBoolean("nav_most_recent", false))
        mNavigationView.getMenu().findItem(R.id.nav_most_recent).setVisible(false);
    if (!mPreferences.getBoolean("nav_events", false))
        mNavigationView.getMenu().findItem(R.id.nav_events).setVisible(false);
    if (!mPreferences.getBoolean("nav_photos", false))
        mNavigationView.getMenu().findItem(R.id.nav_photos).setVisible(false);
    if (!mPreferences.getBoolean("nav_back", false))
        mNavigationView.getMenu().findItem(R.id.nav_back).setVisible(false);
    if (!mPreferences.getBoolean("nav_exitapp", false))
        mNavigationView.getMenu().findItem(R.id.nav_exitapp).setVisible(false);
    if (!mPreferences.getBoolean("nav_top_stories", false))
        mNavigationView.getMenu().findItem(R.id.nav_top_stories).setVisible(false);
    if (!mPreferences.getBoolean("nav_friendreq", false))
        mNavigationView.getMenu().findItem(R.id.nav_friendreq).setVisible(false);
    // Start the Swipe to reload listener
    swipeView = findViewById(R.id.swipeLayout);
    swipeView.setColorSchemeResources(android.R.color.white);
    swipeView.setProgressBackgroundColorSchemeColor(Theme.getColor(this));
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });
    // Inflate the FAB menu
    mMenuFAB = findViewById(R.id.menuFAB);
    View.OnClickListener mFABClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch(v.getId()) {
                case R.id.textFAB:
                    mWebView.loadUrl("javascript:(function(){try{document.querySelector('button[name=\"view_overview\"]').click()}catch(_){window.location.href=\"" + baseURL + "?pageload=composer\"}})()");
                    swipeView.setEnabled(false);
                    break;
                case R.id.photoFAB:
                    mWebView.loadUrl("javascript:(function(){try{document.querySelector('button[name=\"view_photo\"]').click()}catch(_){window.location.href=\"" + baseURL + "?pageload=composer_photo\"}})()");
                    swipeView.setEnabled(false);
                    break;
                case R.id.checkinFAB:
                    mWebView.loadUrl("javascript:(function(){try{document.querySelector('button[name=\"view_location\"]').click()}catch(_){window.location.href=\"" + baseURL + "?pageload=composer_checkin\"}})()");
                    swipeView.setEnabled(false);
                    break;
                case R.id.topFAB:
                    mWebView.scrollTo(0, 0);
                    break;
                case R.id.shareFAB:
                    Intent shareIntent = new Intent(Intent.ACTION_SEND);
                    shareIntent.setType("text/plain");
                    shareIntent.putExtra(Intent.EXTRA_TEXT, mWebView.getUrl());
                    startActivity(Intent.createChooser(shareIntent, getString(R.string.context_share_link)));
                    break;
                default:
                    break;
            }
            mMenuFAB.close(true);
        }
    };
    findViewById(R.id.textFAB).setOnClickListener(mFABClickListener);
    findViewById(R.id.photoFAB).setOnClickListener(mFABClickListener);
    findViewById(R.id.checkinFAB).setOnClickListener(mFABClickListener);
    findViewById(R.id.topFAB).setOnClickListener(mFABClickListener);
    findViewById(R.id.shareFAB).setOnClickListener(mFABClickListener);
    mWebView.setOnScrollChangedCallback(new MFBWebView.OnScrollChangedCallback() {

        @Override
        public void onScrollChange(WebView view, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            // Make sure the hiding is enabled and the scroll was significant
            if (Math.abs(oldScrollY - scrollY) > getApplication().getResources().getDimensionPixelOffset(R.dimen.fab_scroll_threshold)) {
                if (scrollY > oldScrollY) {
                    // User scrolled down, hide the button
                    mMenuFAB.hideMenuButton(true);
                } else if (scrollY < oldScrollY) {
                    // User scrolled up, show the button
                    mMenuFAB.showMenuButton(true);
                }
            }
        }
    });
    mWebView.getSettings().setGeolocationEnabled(mPreferences.getBoolean("location_enabled", false));
    mWebView.addJavascriptInterface(new JavaScriptInterfaces(this), "android");
    mWebView.addJavascriptInterface(this, "Vid");
    mWebView.getSettings().setBlockNetworkImage(mPreferences.getBoolean("stop_images", false));
    mWebView.getSettings().setAppCacheEnabled(true);
    mWebView.getSettings().setUseWideViewPort(true);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setAllowContentAccess(true);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    if (Build.VERSION.SDK_INT >= 19)
        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    else
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
    mWebView.getSettings().setUserAgentString("Mozilla/5.0 (Linux; Android 6.0) AppleWebKit/537.10+ (KHTML, like Gecko) Version/10.1.0.4633 Mobile Safari/537.10+");
    mWebView.setWebViewClient(new WebViewClient() {

        @SuppressLint("NewApi")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return shouldOverrideUrlLoading(view, request.getUrl().toString());
        }

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                // clean an url from facebook redirection before processing (no more blank pages on back)
                url = Helpers.cleanAndDecodeUrl(url);
                if (url.contains("mailto:")) {
                    Intent mailto = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(mailto);
                }
                if ((Uri.parse(url).getHost().endsWith("facebook.com") || Uri.parse(url).getHost().endsWith("*.facebook.com") || Uri.parse(url).getHost().endsWith("akamaihd.net") || Uri.parse(url).getHost().endsWith("ad.doubleclick.net") || Uri.parse(url).getHost().endsWith("sync.liverail.com") || Uri.parse(url).getHost().endsWith("cdn.fbsbx.com") || Uri.parse(url).getHost().endsWith("lookaside.fbsbx.com"))) {
                    return false;
                }
                if (url.contains("giphy") || url.contains("gifspace") || url.contains("tumblr") || url.contains("gph.is") || url.contains("gif") || url.contains("fbcdn.net") || url.contains("imgur")) {
                    if (url.contains("giphy") || url.contains("gph")) {
                        if (!url.endsWith(".gif")) {
                            if (url.contains("giphy.com") || url.contains("html5"))
                                url = String.format("http://media.giphy.com/media/%s/giphy.gif", url.replace("http://giphy.com/gifs/", ""));
                            else if (url.contains("gph.is") && !url.contains("html5")) {
                                view.loadUrl(url);
                                url = String.format("http://media.giphy.com/media/%s/giphy.gif", url.replace("http://giphy.com/gifs/", ""));
                            }
                            if (url.contains("media.giphy.com/media/") && !url.contains("html5")) {
                                String[] giphy = url.split("-");
                                String giphy_id = giphy[giphy.length - 1];
                                url = "http://media.giphy.com/media/" + giphy_id;
                            }
                            if (url.contains("media.giphy.com/media/http://media")) {
                                String[] gph = url.split("/");
                                String gph_id = gph[gph.length - 2];
                                url = "http://media.giphy.com/media/" + gph_id + "/giphy.gif";
                            }
                            if (url.contains("html5/giphy.gif")) {
                                String[] giphy_html5 = url.split("/");
                                String giphy_html5_id = giphy_html5[giphy_html5.length - 3];
                                url = "http://media.giphy.com/media/" + giphy_html5_id + "/giphy.gif";
                            }
                        }
                        if (url.contains("?")) {
                            String[] giphy1 = url.split("\\?");
                            String giphy_html5_id = giphy1[0];
                            url = giphy_html5_id + "/giphy.gif";
                        }
                    }
                    if (url.contains("gifspace")) {
                        if (!url.endsWith(".gif"))
                            url = String.format("http://gifspace.net/image/%s.gif", url.replace("http://gifspace.net/image/", ""));
                    }
                    if (url.contains("phygee")) {
                        if (!url.endsWith(".gif")) {
                            getSrc(url, "span", "img");
                            url = "http://www.phygee.com/" + elements.attr("src");
                        }
                    }
                    if (url.contains("imgur")) {
                        if (!url.endsWith(".gif") && !url.endsWith(".jpg")) {
                            getSrc(url, "div.post-image", "img");
                            url = "https:" + elements.attr("src");
                        }
                    }
                    if (url.contains("media.upgifs.com")) {
                        if (!url.endsWith(".gif")) {
                            getSrc(url, "div.gif-pager-container", "img#main-gif");
                            url = elements.attr("src");
                        }
                    }
                    imageLoader(url, view.getTitle());
                    return true;
                } else {
                    // Open external links in browser
                    Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(browser);
                    return true;
                }
            } catch (NullPointerException npe) {
                return true;
            }
        }

        private void getSrc(final String url, final String select, final String select2) {
            new AsyncTask<Void, Void, Void>() {

                @Override
                protected Void doInBackground(Void[] params) {
                    try {
                        Document document = Jsoup.connect(url).get();
                        elements = document.select(select).select(select2);
                    } catch (IOException ioex) {
                        ioex.getStackTrace();
                    }
                    return null;
                }
            }.execute();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            swipeView.setRefreshing(true);
            if (url.contains("https://mbasic.facebook.com/home.php?s="))
                view.loadUrl(baseURL);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            JavaScriptHelpers.videoView(view);
            if (swipeView.isRefreshing())
                JavaScriptHelpers.loadCSS(view, css);
            if (url.contains("facebook.com/composer/mbasic/") || url.contains("https://m.facebook.com/sharer.php?sid="))
                css += "#page{top:0}";
            if (url.contains("/photos/viewer/")) {
                mWebView.loadUrl(baseURL + "photo/view_full_size/?fbid=" + url.substring(url.indexOf("photo=") + 6).split("&")[0]);
                goBack = true;
            }
            if (url.contains("photo.php?fbid=")) {
                mWebView.loadUrl(baseURL + "photo/view_full_size/?fbid=" + url.substring(url.indexOf("fbid=") + 5).split("&")[0]);
                goBack = true;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            swipeView.setRefreshing(false);
            switch(mPreferences.getString("web_themes", "Material")) {
                case "FacebookMobile":
                    break;
                case "Material":
                    css += getString(R.string.Material);
                    break;
                case "MaterialAmoled":
                    css += getString(R.string.MaterialAmoled);
                    css += "::selection {background: #D3D3D3;}";
                    break;
                case "MaterialBlack":
                    css += getString(R.string.MaterialBlack);
                    break;
                case "MaterialPink":
                    css += getString(R.string.MaterialPink);
                    break;
                case "MaterialGrey":
                    css += getString(R.string.MaterialGrey);
                    break;
                case "MaterialGreen":
                    css += getString(R.string.MaterialGreen);
                    break;
                case "MaterialRed":
                    css += getString(R.string.MaterialRed);
                    break;
                case "MaterialLime":
                    css += getString(R.string.MaterialLime);
                    break;
                case "MaterialYellow":
                    css += getString(R.string.MaterialYellow);
                    break;
                case "MaterialPurple":
                    css += getString(R.string.MaterialPurple);
                    break;
                case "MaterialLightBlue":
                    css += getString(R.string.MaterialLightBlue);
                    break;
                case "MaterialOrange":
                    css += getString(R.string.MaterialOrange);
                    break;
                case "MaterialGooglePlayGreen":
                    css += getString(R.string.MaterialGPG);
                    break;
                default:
                    break;
            }
            if (url.contains("lookaside") || url.contains("cdn.fbsbx.com")) {
                Url = url;
                RequestStoragePermission();
            }
            // Enable or disable FAB
            if (url.contains("messages") || !mPreferences.getBoolean("fab_enable", false))
                mMenuFAB.setVisibility(View.GONE);
            else
                mMenuFAB.setVisibility(View.VISIBLE);
            if (url.contains("https://mbasic.facebook.com/composer/?text=")) {
                final UrlQuerySanitizer sanitizer = new UrlQuerySanitizer();
                sanitizer.setAllowUnregisteredParamaters(true);
                sanitizer.parseUrl(url);
                final String param = sanitizer.getValue("text");
                view.loadUrl("javascript:(function(){document.querySelector('#composerInput').innerHTML='" + param + "'})()");
            }
            if (url.contains("https://m.facebook.com/public/")) {
                String[] user = url.split("/");
                String profile = user[user.length - 1];
                view.loadUrl("javascript:(function(){document.querySelector('input#u_0_0._5whq.input').value='" + profile + "'})()");
                view.loadUrl("javascript:(function(){try{document.querySelector('button#u_0_1.btn.btnD.mfss.touchable').disabled = false}catch(_){}})()");
                view.loadUrl("javascript:(function(){try{document.querySelector('button#u_0_1.btn.btnD.mfss.touchable').click()}catch(_){}})()");
            }
            // Hide Orange highlight on focus
            css += "*{-webkit-tap-highlight-color:transparent;outline:0}";
            if (mPreferences.getBoolean("hide_menu_bar", true))
                css += "#page{top:-45px}";
            // Hide the status editor on the News Feed if setting is enabled
            if (mPreferences.getBoolean("hide_editor_newsfeed", true))
                css += "#mbasic_inline_feed_composer{display:none}";
            // Hide 'Sponsored' content (ads)
            if (mPreferences.getBoolean("hide_sponsored", true))
                css += "article[data-ft*=ei]{display:none}";
            // Hide birthday content from News Feed
            if (mPreferences.getBoolean("hide_birthdays", true))
                css += "article#u_1j_4{display:none}" + "article._55wm._5e4e._5fjt{display:none}";
            if (mPreferences.getBoolean("comments_recently", true))
                css += "._15ks+._4u3j{display:none}";
            css += "._i81:after {display: none;}";
            if (sharedFromGallery != null)
                view.loadUrl("javascript:(function(){try{document.getElementsByClassName(\"_56bz _54k8 _52jh _5j35 _157e\")[0].click()}catch(_){document.getElementsByClassName(\"_50ux\")[0].click()}})()");
            css += "article#u_0_q._d2r{display:none}";
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
            // Double check that we don't have any existing callbacks
            if (sharedFromGallery != null)
                filePathCallback.onReceiveValue(new Uri[] { sharedFromGallery });
            mFilePathCallback = filePathCallback;
            // Set up the take picture intent
            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                // Error occurred while creating the File
                }
                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else
                    takePictureIntent = null;
            }
            // Set up the intent to get an existing image
            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("*/*");
            // Set up the intents for the Intent chooser
            Intent[] intentArray;
            if (takePictureIntent != null)
                intentArray = new Intent[] { takePictureIntent };
            else
                intentArray = new Intent[0];
            if (sharedFromGallery == null) {
                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
            }
            return true;
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

        // openFileChooser for Android 3.0+
        private void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            // Update message
            if (sharedFromGallery != null)
                uploadMsg.onReceiveValue(sharedFromGallery);
            else
                mUploadMessage = uploadMsg;
            File imageStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            if (!imageStorageDir.exists()) {
                imageStorageDir.mkdirs();
            }
            // Create camera captured image file path and name
            File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
            mCapturedImageURI = Uri.fromFile(file);
            // Camera capture image intent
            final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            if (sharedFromGallery == null) {
                Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });
                startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
            }
        }

        private File createImageFile() throws IOException {
            // Create an image file name
            final String imageFileName = "JPEG_" + String.valueOf(System.currentTimeMillis()) + "_";
            File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            final File imageFile = File.createTempFile(imageFileName, ".jpg", storageDir);
            return imageFile;
        }

        public void onGeolocationPermissionsShowPrompt(final String origin, final GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (view.getUrl().contains("home.php?sk=h_nor"))
                setTitle(R.string.menu_top_stories);
            else if (title.contains("Facebook"))
                setTitle(R.string.menu_most_recent);
            else
                setTitle(title);
        }
    });
    // Add OnClick listener to Profile picture
    ImageView profileImage = mNavigationView.getHeaderView(0).findViewById(R.id.profile_picture);
    profileImage.setClickable(true);
    profileImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            drawer.closeDrawers();
            mWebView.loadUrl(baseURL + "me");
        }
    });
    mDownloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    if (getIntent() != null)
        UrlIntent(getIntent());
}
Also used : ValueCallback(android.webkit.ValueCallback) GeolocationPermissions(android.webkit.GeolocationPermissions) ActionBarDrawerToggle(android.support.v7.app.ActionBarDrawerToggle) Cursor(android.database.Cursor) Document(org.jsoup.nodes.Document) SwipeRefreshLayout(android.support.v4.widget.SwipeRefreshLayout) Uri(android.net.Uri) BookmarksH(me.zeeroooo.materialfb.Misc.BookmarksH) MFBWebView(me.zeeroooo.materialfb.WebView.MFBWebView) ImageButton(android.widget.ImageButton) Bitmap(android.graphics.Bitmap) WebChromeClient(android.webkit.WebChromeClient) JavaScriptInterfaces(me.zeeroooo.materialfb.WebView.JavaScriptInterfaces) ImageView(android.widget.ImageView) WebView(android.webkit.WebView) MFBWebView(me.zeeroooo.materialfb.WebView.MFBWebView) Toolbar(android.support.v7.widget.Toolbar) WebViewClient(android.webkit.WebViewClient) BookmarksAdapter(me.zeeroooo.materialfb.Misc.BookmarksAdapter) WebResourceRequest(android.webkit.WebResourceRequest) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) Parcelable(android.os.Parcelable) IOException(java.io.IOException) NavigationView(android.support.design.widget.NavigationView) SearchView(android.support.v7.widget.SearchView) ImageView(android.widget.ImageView) View(android.view.View) AdapterView(android.widget.AdapterView) WebView(android.webkit.WebView) MFBWebView(me.zeeroooo.materialfb.WebView.MFBWebView) TextView(android.widget.TextView) ListView(android.widget.ListView) SuppressLint(android.annotation.SuppressLint) Point(android.graphics.Point) DatabaseHelper(me.zeeroooo.materialfb.Misc.DatabaseHelper) SuppressLint(android.annotation.SuppressLint) AdapterView(android.widget.AdapterView) File(java.io.File) UrlQuerySanitizer(android.net.UrlQuerySanitizer)

Example 33 with WebResourceRequest

use of android.webkit.WebResourceRequest in project Awful.apk by Awful.

the class PreviewFragment method configureWebView.

public void configureWebView() {
    postPreView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest wrr) {
            return true;
        }
    });
    postPreView.setJavascriptHandler(jsInterface);
}
Also used : WebResourceRequest(android.webkit.WebResourceRequest) AwfulWebView(com.ferg.awfulapp.webview.AwfulWebView) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 34 with WebResourceRequest

use of android.webkit.WebResourceRequest in project edx-app-android by edx.

the class CertificateFragment method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_certificate, container, false);
    webview = (WebView) view.findViewById(R.id.webview);
    final View loadingIndicator = view.findViewById(R.id.loading_indicator);
    final URLInterceptorWebViewClient client = new URLInterceptorWebViewClient(getActivity(), webview);
    client.setPageStatusListener(new URLInterceptorWebViewClient.IPageStatusListener() {

        @Override
        public void onPageStarted() {
            loadingIndicator.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished() {
            loadingIndicator.setVisibility(View.GONE);
        }

        @Override
        public void onPageLoadError(WebView view, int errorCode, String description, String failingUrl) {
            loadingIndicator.setVisibility(View.GONE);
        }

        @Override
        public void onPageLoadError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse, boolean isMainRequestFailure) {
            if (isMainRequestFailure) {
                loadingIndicator.setVisibility(View.GONE);
            }
        }

        @Override
        public void onPagePartiallyLoaded() {
            loadingIndicator.setVisibility(View.GONE);
        }
    });
    return view;
}
Also used : WebResourceRequest(android.webkit.WebResourceRequest) WebResourceResponse(android.webkit.WebResourceResponse) WebView(android.webkit.WebView) View(android.view.View) WebView(android.webkit.WebView) URLInterceptorWebViewClient(org.edx.mobile.view.custom.URLInterceptorWebViewClient)

Example 35 with WebResourceRequest

use of android.webkit.WebResourceRequest in project AgentWeb by Justson.

the class JsbridgeWebFragment method getWebViewClient.

private WebViewClient getWebViewClient() {
    return new WebViewClient() {

        BridgeWebViewClient mBridgeWebViewClient = new BridgeWebViewClient(mBridgeWebView);

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return mBridgeWebViewClient.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (mBridgeWebViewClient.shouldOverrideUrlLoading(view, request.getUrl().toString())) {
                return true;
            } else {
                return super.shouldOverrideUrlLoading(view, request);
            }
        }

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

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mBridgeWebViewClient.onPageFinished(view, url);
        }
    };
}
Also used : Bitmap(android.graphics.Bitmap) WebResourceRequest(android.webkit.WebResourceRequest) BridgeWebViewClient(com.github.lzyzsd.jsbridge.BridgeWebViewClient) BridgeWebView(com.github.lzyzsd.jsbridge.BridgeWebView) WebView(android.webkit.WebView) BridgeWebViewClient(com.github.lzyzsd.jsbridge.BridgeWebViewClient) WebViewClient(com.just.agentweb.WebViewClient)

Aggregations

WebResourceRequest (android.webkit.WebResourceRequest)38 WebView (android.webkit.WebView)37 WebViewClient (android.webkit.WebViewClient)34 Bitmap (android.graphics.Bitmap)22 WebResourceError (android.webkit.WebResourceError)21 WebResourceResponse (android.webkit.WebResourceResponse)16 WebSettings (android.webkit.WebSettings)14 Intent (android.content.Intent)13 View (android.view.View)12 WebChromeClient (android.webkit.WebChromeClient)12 SuppressLint (android.annotation.SuppressLint)11 TextView (android.widget.TextView)9 SslError (android.net.http.SslError)8 SslErrorHandler (android.webkit.SslErrorHandler)8 Uri (android.net.Uri)7 TargetApi (android.annotation.TargetApi)6 IOException (java.io.IOException)5 Nullable (android.support.annotation.Nullable)3 SearchView (android.support.v7.widget.SearchView)3 Toolbar (android.support.v7.widget.Toolbar)3