React-native-WebView setItem()from localStorage no working

vfhzx4xs  于 6个月前  发布在  React
关注(0)|答案(1)|浏览(99)

我想在React Native app打开的页面需要检查localStorage,其中存储了user tokenuser rolesuser permissions。因此,在加载页面之前,需要在localStorage中设置token和其他相关值。
我在react-native-webview中使用了prop injectedJavaScriptBeforeContentLoaded,但没有工作。

这是我的代码

const runFirst = `
      window.localStorage.setItem('api_token', 'zzz');
      window.localStorage.setItem('auth_roles', 'zzz');
      window.localStorage.setItem('auth_permissions', 'zzz');
      setTimeout(function() { window.alert('hi') }, 1000);
      true; // note: this is required, or you'll sometimes get silent failures
    `;

    return (
        <NativeBaseProvider>
            <WebView
                startInLoadingState={true}
                source={{
                    //uri: 'https://github.com/react-native-webview/react-native-webview',
                    uri:'xxxxxx'
                }}
                injectedJavaScriptBeforeContentLoaded={runFirst}
                onMessage={(event) => {}}
                style={{width:screenWidth, height:screenHeight}}
            />
        </NativeBaseProvider>
    );

字符串

密码

setTimeout(function() { window.alert('hi') }, 1000);


将被处决,但

window.localStorage.setItem


没有被处决
打开的页面是空白的。
如果我删除有关window.localSotrage.setItem的代码,打开的页面将正常。
设备:三星Galaxy A34 5G
操作系统:Android
操作系统:Android 9
react-native版本:0.71.13
react-native-webview版本:13.6.2
我已经尝试并阅读了关于React-Native-WebView injectedJavaScriptBeforeContentLoaded的资源:

我在寻找一些解决方案或帮助

yftpprvb

yftpprvb1#

您是否尝试过等待文档加载后再访问localStorage

window.onload = function(){
      window.localStorage.setItem('api_token', 'zzz');
      window.localStorage.setItem('auth_roles', 'zzz');
      window.localStorage.setItem('auth_permissions', 'zzz');
      setTimeout(function() { window.alert('hi') }, 1000);
    }

字符串
可能是因为超时,警报才起作用。

相关问题