【问题标题】:React Native Webview - injectJavascript not workingReact Native Webview - 注入Javascript不起作用
【发布时间】:2021-05-07 03:07:42
【问题描述】:

我试图在加载 React Native Webview 的内容之前注入 JS 代码以提醒用户,但是,对我来说,它只是转到活动指示器并加载 Webview 而不注入任何 Javascript。我该如何解决?代码如下:

import React from 'react';
import { View, ActivityIndicator } from 'react-native';
import { WebView } from 'react-native-webview';
import styles from '../../styles';

export default function Links() {

  function LoadingIndicatorView() {
    return (
      <View style={styles.hubLoading}>
        <ActivityIndicator color='#009b88' size='large' />
      </View>
    )  
  }

  const runFirst = `
      setTimeout(function() { window.alert('hi') }, 2000);
      true; // note: this is required, or you'll sometimes get silent failures
    `

  return <WebView source={{ uri: https://www.google.com/ }} renderLoading={LoadingIndicatorView} startInLoadingState={true} javaScriptEnabled={true} injectedJavaScript={runFirst} />;
}

顺便说一句,如果这有助于您回答,我正在我的 iOS 设备上运行该应用程序。

【问题讨论】:

  • 我的回答能帮到你吗?如果是,请接受答案。如果没有,请提供更多信息以便我们为您提供帮助。

标签: javascript react-native react-native-webview


【解决方案1】:

您应该在WebView 中包含onMessage={(event) =&gt; {}}

https://github.com/react-native-webview/react-native-webview/blob/master/docs/Guide.md

还需要一个 onMessage 事件来将 JavaScript 代码注入 WebView。

<WebView 
      source={{ uri: "https://www.google.com/" }}
      renderLoading={LoadingIndicatorView}
      startInLoadingState={true}
      javaScriptEnabled={true}
      injectedJavaScript={runFirst}
      onMessage={(event) => {}}
/>

【讨论】:

    【解决方案2】:
    猜你喜欢
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2017-04-30
    • 1970-01-01
    • 1970-01-01
    • 2020-05-20
    相关资源
    最近更新 更多