react open linking react-native

open - React Native: enlaces abiertos en el navegador



web views react native (6)

Hola, estoy usando la vista web de reaccionar native para mostrar algunos html, quiero que cada vez que un usuario haga clic en un enlace dentro de ese html, abra el navegador del usuario con ese enlace.

¿es eso posible?

Editar 1:

Terminé usando este paquete: npmjs.com/package/react-native-communications que abre el navegador. Llamo al navegador para que abra onNavigationStateChange cuando cambia la URL.

Ahora, la WebView sigue procesando la solicitud, aunque me he mudado al navegador. ¿Cómo puedo detener la solicitud?


Encontré una manera de hacer esto, ¡aunque es una solución solo para iOS!

Aquí hay instrucciones paso a paso:

  1. Enlace la biblioteca ''RCTLinkingIOS'' a su proyecto. Usé CocoaPods para eso.
  2. En su WebView agregue "onShouldStartLoadWithRequest". Por ejemplo

    <WebView source={{ html: content }} onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest} />

  3. Agregue la función this.onShouldStartLoadWithRequest . Devuelve VERDADERO o FALSO según si quieres seguir el enlace en tu WebView. Esto es básicamente el equivalente de la implementación UIWebViewDelegate que usaría cuando lo implemente en código nativo (Swift u Objective-C).

    onShouldStartLoadWithRequest = (event) => { Linking.canOpenURL(event.url).then(supported => { if (supported) { Linking.openURL(event.url); } else { console.log(''Don/'t know how to open URI: '' + event.url); } return false }); }

  4. Asegúrese de importar Linking también en su fuente de JavaScript:

    import { AppRegistry, View, WebView, Linking } from ''react-native'';

Eso debería hacer el truco.

Para obtener más información, consulte los documentos nativos de reactivos: https://facebook.github.io/react-native/docs/linking.html


Es posible hacerlo de forma multiplataforma utilizando la clase https://facebook.github.io/react-native/docs/linking.html react-native-webview-bridge .

const generateLink = (text, url) => { if (url) { return `<a href=''#'' onclick=''WebViewBridge.send("${url}"); return false;''>${text}</a>`; } else { return text; } }; const generateHtml = () => `<!DOCTYPE html><html><body> ${generateLink(''Link text'', ''http://example.com'')} </body></html>`;

Con un componente WebViewBridge procesado así:

<WebViewBridge javaScriptEnabled renderLoading={() => <ActivityIndicator animating size="large" />} source={{ html: generateHtml() }} onBridgeMessage={url => Linking.openURL(url)} />


Esta es mi solución. Como no es genérico, puede mejorar el javascript inyectado según sus requisitos

import { View, WebView, Linking, } from ''react-native''; const injectScript = ` (function () { window.onclick = function(e) { e.preventDefault(); window.postMessage(e.target.href); e.stopPropagation() } }()); `; class MyWebView extends React.Component { onMessage({ nativeEvent }) { const data = nativeEvent.data; if (data !== undefined && data !== null) { Linking.openURL(data); } } render() { return ( <WebView source={{ html: this.props.html }} injectedJavaScript={injectScript} onMessage={this.onMessage} /> ) } }



Aquí hay una solución de trabajo completa:

import React, { Component } from ''react''; import { WebView, Linking } from ''react-native''; export default class WebViewThatOpensLinksInNavigator extends Component { render() { const uri = ''http://.com/questions/35531679/react-native-open-links-in-browser''; return ( <WebView ref={(ref) => { this.webview = ref; }} source={{ uri }} onNavigationStateChange={(event) => { if (event.url !== uri) { this.webview.stopLoading(); Linking.openURL(event.url); } }} /> ); } }

Utiliza una WebView simple, intercepta cualquier cambio de url y, si esa url difiere de la original, detiene la carga, lo que evita el cambio de página y, en su lugar, lo abre en el OS Navigator.