【问题标题】:I'm trying to call a function defined on the web, but nothing happens我正在尝试调用网络上定义的函数,但没有任何反应
【发布时间】:2023-02-07 15:20:46
【问题描述】:

我正在尝试使用 React Native WebView 打开一个简单的页面。 这是一个单页网络,当您进行搜索时,它会打印出一些关于您的搜索的信息。

之后,如果您想再次搜索,请按设备上的后退按钮移动到搜索框。

因为它是单页,我不能使用 goBack,所以我创建了一个名为 cancel 的函数。

问题是当我点击设备的后退按钮时,没有执行在网络上定义的名为取消的功能。

取消功能删除搜索到的信息并返回到搜索窗口。

我会上传我的代码。

请指教。

export default function App() {
  const webviewRef = useRef(null);
  
  const backAction = () => {
    setBackTapping((prev) => prev += 1);
    webviewRef.current.injectJavaScript('window.cancel()')
    return true;
  }

  useEffect(() => {
    const timer = setInterval(() => {
      setBackTapping(0)
    }, 1000)
    return () => clearInterval(timer);
  }, [])

  useEffect(() => {
    const backHandler = BackHandler.addEventListener('hardwareBackPress',backAction);
    return () => backHandler.remove()
  }, [])

  useEffect(() => {
    if(backTapping >= 2){
      return BackHandler.exitApp();
    }
  },[backTapping])
  

  return (
    <KeyboardAvoidingView style={{ flex: 1 }}>
    <StatusBar hidden />
    
    <WebView
      ref={webviewRef}
      textZoom={100}
      originWhitelist={['*']}
      javaScriptEnabled
      source={{ uri: 'myhome.com'}}
      startInLoadingState={true}
    />
    </KeyboardAvoidingView>
  );
}

预期行为:

执行取消函数,关闭所有打开的窗口,返回到搜索窗口。

【问题讨论】:

    标签: react-native react-native-webview


    【解决方案1】:

    就我而言,调用是错误的。

    代替 :

    webviewRef.current.injectJavaScript('window.cancel()')
    

    使用 :

      const generateOnMessageFunction = (data) => `
        (function(){
          window.dispatchEvent(new MessageEvent('message',{data: ${JSON.stringify(data)}}));
        })()
      `;
      webviewRef.current.injectJavaScript(generateOnMessageFunction('cancel'));
    

    详细参考: https://github.com/react-native-webview/react-native-webview/issues/809

    【讨论】:

      猜你喜欢
      • 2018-05-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-22
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 2016-06-29
      • 1970-01-01
      相关资源
      最近更新 更多