【问题标题】:React-native: how to save webview current web page aoutomaticaly?React-native:如何自动保存 webview 当前网页?
【发布时间】:2021-09-23 21:26:05
【问题描述】:

我是 React Native 的新手。 我正在尝试在我的 react-native 应用程序(Android)中使用 WebView。它工作得很好。我想,在 webview 中加载网页后,它会自动保存为本地文件。 请帮帮我。

编辑:我想要,应用程序将网页保存为本地文件,而不是保存 URL。

【问题讨论】:

    标签: android ios react-native webview android-webview


    【解决方案1】:

    我猜你正在使用react-native-webview

    有一个道具调用onNavigationStateChange

    例如,您可以将 url 保存到 AsyncStorage

    const storeData = async (url) => {
      try {
        await AsyncStorage.setItem(
          'lastURL',
          url
        );
      } catch (error) {
        // Error saving data
      }
    };
    
    ...
    <WebView
    ...
    onNavigationStateChange={(navState) => {
        const { url } = navState;
        storeData(url)
      }}
    />
    

    ======= 编辑 ======= 如果你只想要 html。

    import * as React from 'react';
    import { WebView } from 'react-native-webview';
    import { View, Text } from 'react-native';
    
    export default function App() {
      const injectedJavascript = `(function() {
          window.postMessage = function(data) {
        window.ReactNativeWebView.postMessage(data);
        return true;
      };
      window.postMessage(new XMLSerializer().serializeToString(document))
    })()`
    const saveHTML = (htmlString)=>{
      ...
    }
      return (
        <View
          style={{
            flex: 1,
          }}>
          <WebView
            originWhitelist={['*']}
            javaScriptEnabled={true}
            injectedJavaScript={injectedJavascript}
            onMessage={e => {saveHTML(e.nativeEvent.data)}}
            source={{
              uri: 'https://google.com'
            }}
          />
        </View>
      );
    }
    
    

    【讨论】:

    • 感谢您回答我的问题。‌‌但我不想保存 URL。我想将网页保存在文件中。
    • 哎呀,对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2017-06-07
    • 2020-06-09
    • 2019-05-11
    • 2020-12-13
    • 2019-03-13
    相关资源
    最近更新 更多