web-dev-qa-db-fra.com

Existe-t-il un moyen de forcer l’ouverture d’un lien dans Chrome?

Je teste actuellement une application Web développée avec de nombreuses animations jQuery et nous avons constaté de très mauvaises performances avec le navigateur Web intégré. Lors des tests dans Chrome, les performances de l'application Web sont incroyablement plus rapides. Je me demandais simplement s'il existait un type de script qui obligerait à ouvrir un lien dans Chrome pour Android, de la même manière que dans iOS.

52
user1607943

Une méthode plus élégante consiste à utiliser l’intention Intent.ACTION_VIEW normalement, mais à ajouter le package com.Android.chrome à l’intention. Cela fonctionne indépendamment du fait que Chrome soit le navigateur par défaut et garantit exactement le même comportement que si l'utilisateur avait sélectionné Chrome dans la liste du sélecteur.

String urlString = "http://mysuperwebsite";
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(urlString));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage("com.Android.chrome");
try {
    context.startActivity(intent);
} catch (ActivityNotFoundException ex) {
    // Chrome browser presumably not installed so allow user to choose instead
    intent.setPackage(null);
    context.startActivity(intent);
}

Mettre à jour

Pour les appareils Kindle:

Juste au cas où vous voudriez ouvrir Amazon Default Browser au cas où l'application Chrome ne serait pas installée dans Amazon Kindle

String urlString = "http://mysuperwebsite";
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(urlString));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setPackage("com.Android.chrome");
try {
    context.startActivity(intent);
} catch (ActivityNotFoundException ex) {
    // Chrome browser presumably not installed and open Kindle Browser
    intent.setPackage("com.Amazon.cloud9");
    context.startActivity(intent);
}
58
Martin

Il y a deux solutions.

Par colis

    String url = "http://www.example.com";
    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i.setPackage("com.Android.chrome");
    try {
        startActivity(i);
    } catch (ActivityNotFoundException e) {
        // Chrome is probably not installed
        // Try with the default browser
        i.setPackage(null);
        startActivity(i);
    }

Par régime

    String url = "http://www.example.com";
    try {
        Uri uri = Uri.parse("googlechrome://navigate?url=" + url);
        Intent i = new Intent(Intent.ACTION_VIEW, uri);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
    } catch (ActivityNotFoundException e) {
        // Chrome is probably not installed
    }

ATTENTION! La technique suivante ne fonctionne pas sur les versions les plus récentes d'Android. C'est ici pour référence, car cette solution existe depuis un moment:

    String url = "http://www.example.com";
    try {
        Intent i = new Intent("Android.intent.action.MAIN");
        i.setComponent(ComponentName.unflattenFromString("com.Android.chrome/com.Android.chrome.Main"));
        i.addCategory("Android.intent.category.LAUNCHER");
        i.setData(Uri.parse(url));
        startActivity(i);
    }
    catch(ActivityNotFoundException e) {
        // Chrome is probably not installed
    }
41
philippe_b

Toutes les solutions proposées ne fonctionnent plus pour moi. Grâce à @pixelbandito, il m'a dirigé dans la bonne direction. J'ai trouvé la prochaine constante dans les sources de chrome

public static final String GOOGLECHROME_NAVIGATE_PREFIX = "googlechrome://navigate?url=";

Et la prochaine utilisation:

 Intent intent = new Intent("Android.intent.action.VIEW", Uri.parse("googlechrome://navigate?url=chrome-native://newtab/"));

Donc la solution est (notez que l'URL ne doit pas être encodé)

void openUrlInChrome(String url) {
    try {
        try {
            Uri uri = Uri.parse("googlechrome://navigate?url="+ url);
            Intent i = new Intent(Intent.ACTION_VIEW, uri);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        } catch (ActivityNotFoundException e) {
            Uri uri = Uri.parse(url);
            // Chrome is probably not installed
            // OR not selected as default browser OR if no Browser is selected as default browser
            Intent i = new Intent(Intent.ACTION_VIEW, uri);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);
        }
    } catch (Exception ex) {
        Timber.e(ex, null);
    }
}
8
httpdispatch

Cela fonctionne dans Firefox et Opera

document.location = 'googlechrome://navigate?url=www.example.com/';

6
Tim Smith

Suite à la réponse de @ philippe_b, je voudrais ajouter que ce code ne fonctionnera pas si Chrome n'est pas installé. Dans un cas supplémentaire, cela ne fonctionnera pas: c'est le cas lorsque Chrome n'est PAS sélectionné comme navigateur par défaut (mais qu'il est installé) OR même si aucun navigateur n'est sélectionné par défaut.

Dans ce cas, ajoutez également la partie suivante du code qui concerne les captures.

try {
    Intent i = new Intent("Android.intent.action.MAIN");
    i.setComponent(ComponentName.unflattenFromString("com.Android.chrome/com.Android.chrome.Main"));
   i.addCategory("Android.intent.category.LAUNCHER");
    i.setData(Uri.parse("http://mysuperwebsite"));
    startActivity(i);
}
catch(ActivityNotFoundException e) {
// Chrome is probably not installed 
// OR not selected as default browser OR if no Browser is selected as default browser
    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("somesite.com"));
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
}

2
user1406716

Voici ce que j'ai trouvé de plus proche: écrire une URL et remplacer http par googlechrome ouvrira Chrome, mais il ne semble pas ouvrir l'url spécifié. Je travaille avec un Samsung Galaxy S5, Android 5.0

C'est ce que j'ai trouvé de mieux. Toutes les autres solutions que j'ai vues sur SO nécessitent une application Android, pas une application Web.

2
pixelbandito

Dans Google Play, il existe une grande variété d'applications de navigateur Chrome avec différentes fonctionnalités.

Donc, il est correct de tous les vérifier

fun Context.openChrome(url: String, onError: (() -> Unit)? = null) {
    openBrowser("com.Android.chrome", url) {
        openBrowser("com.Android.beta", url) {
            openBrowser("com.Android.dev", url) {
                openBrowser("com.Android.canary", url) {
                    onError?.invoke() ?: openBrowser(null, url)
                }
            }
        }
    }
}

fun Context.openBrowser(packageName: String?, url: String, onError: (() -> Unit)? = null) {
    try {
        startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {
            setPackage(packageName)
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        })
    } catch (e: ActivityNotFoundException) {
        onError?.invoke()
    }
}
0
V. Kalyuzhnyu

Si vous obtenez une erreur concernant la constante TAG, ajoutez ce code à l'activité.

private static final String TAG = "MainActivity";
0
Favourite Videos

Les différentes réponses ci-dessus sont bonnes mais aucune n'est complète. Cela me convenait en tout cas le meilleur qui:

essayez d'ouvrir le navigateur Web Chrome et, en cas d'exception (chrome n'est pas installé par défaut ou n'est pas installé), vous devrez choisir le navigateur de l'utilisateur:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                intent.setPackage("com.Android.chrome");
                try {
                    Log.d(TAG, "onClick: inTryBrowser");
                    startActivity(intent);
                } catch (ActivityNotFoundException ex) {
                    Log.e(TAG, "onClick: in inCatchBrowser", ex );
                    intent.setPackage(null);
                    startActivity(intent.createChooser(intent, "Select Browser"));
                }
0
Tushar Seth