Есть ли способ изменить стили для элементов в веб-документе, которые соответствуют перечисленным типам детекторов данных? - PullRequest
0 голосов
/ 23 мая 2019

React Native Webview позволяет вам определять конкретные типы детекторов данных, включая ссылки на эти типы.В случае, когда документ HTML содержит номер телефона (без тега гиперссылки), нет никаких признаков того, что номер телефона можно активировать нажатием кнопки (в качестве примечания, у меня уже есть логика для связи с родным телефоном, когда номерщелкнул, так что часть работает).Могу ли я изменить стиль этих обнаруженных кликабельных ссылок в веб-просмотре, не анализируя HTML-код, передаваемый мне через API?

Кроме того, событие возвращает мне номер телефона в видеevent.url, которому предшествует 'tel:', но есть также некоторые специальные символы между этим и фактическим номером телефона.Каков наилучший способ убедиться, что вызываемый номер совпадает с тем, что содержится в html-тексте?

Я еще ничего не пробовал - я не могу найти ничего в официальной документации response-native-webview о том, как это сделатьэтого, и я не нашел ничего в stackoverflow.

        import { View, StyleSheet, Linking } from 'react-native';
        import { WebView as RNWebView } from 'react-native-webview';
        import { WebViewSourceHtml } from 'react-native- 
       webview/lib/WebViewTypes';
        import call from 'react-native-phone-call';

        type Props = {
          onHeightChange: (height: number) => void;
          height?: any;
          // TODO: Source is currently hard-coded for proof of concept.
          // Eventually, it will be the Html source as coming from the API.
          source?: WebViewSourceHtml;
          // TODO: until the API is in place, we might want to pass in the 
        message text and create
          // an 'html' file.
          text?: string;
        };

        class WebView extends Component<Props> {
          private webref: any = '';

          render() {
            const myPage: WebViewSourceHtml = {
          html:
            htmlHeader +
            '<span style="font-family:Verdana; font-size:10pt; color:rgb(0,0,0);">Links test...<br></span><span style="font-family:Verdana; font-size:10pt; color:rgb(0,0,0);"><br></span><span style="font-family:Verdana; font-size:10pt; color:rgb(0,0,0);">978-867-5309<br></span><span style="font-family:Verdana; font-size:10pt; color:rgb(0,0,0);"><br></span><a href="https://www.google.com" target="_blank"><span style="font-family:Verdana; font-size:10pt; `enter code here`color:rgb(0,0,0);">https:&#47;&#47;www.google.com</span></a>' +
            htmlFooter
        };

        return (
          <View style={[styles.bodyContent, { height: this.props.height ? this.props.height : 400 }]}>
            <RNWebView
              ref={r => (this.webref = r)}
              originWhitelist={['*']}
              source={this.props.source ? this.props.source : myPage}
              // note: setting this to false will enable pinch/zoom, but if set to true, this scales
              // the entire webview to fit the page, resulting in a very small initial view.
              scalesPageToFit={false}
              dataDetectorTypes={['link', 'phoneNumber']}
              onMessage={event => this.props.onHeightChange(parseInt(event.nativeEvent.data, 10) + 50)}
              // onMessage={event => console.log(event.nativeEvent.data)}
              javaScriptEnabled={true}
              incognito={true}
              onShouldStartLoadWithRequest={event => {
                if (event.url.slice(0, 4) === 'http') {
                  Linking.openURL(event.url);
                  return false;
                } else if (event.url.slice(0, 3) === 'tel') {
                  const callNumber = event.url.slice(4);
                  call({ number: callNumber, prompt: true }).catch(console.error);
                  return false;
                }
                return true;
              }}
              onLoadEnd={e => {
                if (this.webref) {
                  this.webref.injectJavaScript(
                    `window.ReactNativeWebView.postMessage
                      ( JSON.stringify(document.documentElement.clientHeight))`
                  );
                }
              }}
            />
          </View>
        );
      }
    }

    const styles = StyleSheet.create({
      bodyContent: {
        padding: 16
      }
    });

    const htmlHeader: string =
      `<html><head <meta name="viewport" ` +
      `content="width=device-width,initial-scale=1"></head><body>`;

    const htmlFooter: string = `</body></html>`;

    export { WebView };```

I just want to make the text look clickable so that users know they can click on the link to call the number, and safely extract the appropriate number from the event.url data.


Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...