2012-10-03 33 views
11

Tengo un componente WebView que uso para mostrar anuncios HTML en mi aplicación. Cuando el usuario hace clic en un anuncio en WebView, quiero abrir el enlace del anuncio en un navegador externo. ¿Cómo puedo hacer eso?Abrir enlaces en el navegador externo en WebView (WinRT)

Necesito algo así como OnNavigating desde el navegador WP7. Probé el evento Tapped de WebView pero nunca se llama aunque establezca IsTapEnabled = true. Necesito algo como

Respuesta

20

Tendrá que utilizar el evento ScriptNotify para esto. Así es como manejé el escenario (usando NavigateToString). Si está recuperando el contenido de la vista web desde una URL, deberá poder modificar el HTML para que funcione.

  1. Agregar el siguiente código JavaScript a su HTML

    <script type="text/javascript">for (var i = 0; i < document.links.length; i++) { document.links[i].onclick = function() { window.external.notify('LaunchLink:' + this.href); return false; } }</script> 
    

    Esto añade un manejador onclick a todos los eslabones (< a href = "..." > </a >) en la página. window.external.notify es un método de Javascript que funciona en la vista web.

  2. Agregue el controlador de eventos ScriptNotify a la vista web.

    WebView.ScriptNotify += WebView_ScriptNotify; 
    
  3. Declarar el controlador de eventos

    async private void WebView_ScriptNotify(object sender, NotifyEventArgs e) 
    { 
        try 
        { 
         string data = e.Value; 
         if (data.ToLower().StartsWith("launchlink:")) 
         { 
          await Launcher.LaunchUriAsync(new Uri(data.Substring("launchlink:".Length), UriKind.Absolute)); 
         } 
        } 
        catch (Exception) 
        { 
         // Could not build a proper Uri. Abandon. 
        } 
    } 
    

Tenga en cuenta que si utiliza una URL externa, esto tiene que ser añadido a la lista blanca Uris permitido de la vista web (http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.webview.scriptnotify para referencia) .

+0

pero ¿qué pasa con el hipervínculo a los archivos? esto no funciona http://stackoverflow.com/questions/28886198/hyperlink-click-is-not-firing/ –

+0

En ese caso, intente cambiar UriKind.Absolute por UriKind.Relativo – Akinwale

10

Intente controlar el evento NavigationStarting. Aquí puede interceptar y cancelar la carga de URL. Puede filtrar qué enlace abrir en la vista web y cuál abrir en el navegador predeterminado.

private async void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) 
    { 
     if(null != args.Uri && args.Uri.OriginalString == "URL OF INTEREST") 
     { 
      args.Cancel = true; 
      await Launcher.LaunchUriAsync(args.Uri); 
     } 
    } 
+0

¡Gracias! Esto funcionó para mí. –

Cuestiones relacionadas