React Native-在WebView中设置localStorage [英] React Native - Set localStorage in WebView

查看:304
本文介绍了React Native-在WebView中设置localStorage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在加载页面之前在WebView组件中设置localStorage.

I would like to set localStorage in the WebView component before loading the page.

https://facebook.github.io/react-native/docs/webview

我的用例是我的RN应用想要在其附属网站上打开一个页面.该网站通过检查localStorage中的令牌来在加载时进行身份验证.如果令牌不存在,将提示他们登录.好像用户已经登录了该应用程序一样,如果他们避免避免再次登录WebView,则希望使用它.

My use case for this is that my RN app would like to open a page on it's accompanying website. The website authenticates on load by checking for a token in localStorage. If the token isn't there they will be prompted to login. Seen as the user has already logged in on the app I would prefer it if they could avoid logging in again in the WebView.

推荐答案

您可能已经解决了该问题.如果没有,这是我的解决方案.

You might have overcome the issue. If not here is my solution.

您可以使用 WebView injectedJavaScript 属性,并添加javascript代码以在页面加载时添加令牌.

You can use injectedJavaScript property of WebView and add javascript code to add the token on page load.

示例代码段.

  1. 我需要注入的我的自定义Javascript代码.

let myInjectedJs = `(function(){ let tk = window.localStorage.getItem('tokenKey');
      if(!tk || (tk && tk != '${token}')){
        window.localStorage.setItem('tokenKey', '${token}');
        window.location.reload();
      }
    })();`;

代码说明

函数在加载后立即被调用.检查是否已设置 tokenKey .如果未设置,则将其设置为新令牌 $ {token} 并重新加载页面.

Function is called as soon as loaded. Checks if tokenKey is already set. If not set we are setting it to the new token ${token} and reloading the page.

注意:我们需要将函数作为字符串传递给webview中的 injectedJavaScript .

Note: We need to pass function as a string to injectedJavaScript in webview.

  1. 在WebView中使用 myInjectedJs .

<WebView
    ref={webView => { this.refWeb = webView; }}
    javaScriptEnabled={true}
    injectedJavaScript={myInjectedJs}
    ...

希望这能解决您的问题.

Hope this solves your problem.

这篇关于React Native-在WebView中设置localStorage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆