乐闻世界logo
搜索文章和话题

How to clear react native webview cookies?

1个答案

1

In React Native, to clear cookies in WebView, we can utilize the injectJavaScript method provided by react-native-webview or use the react-native-cookies library. Here are examples of both methods:

Method 1: Using injectJavaScript from react-native-webview

When we need to inject JavaScript code into WebView to clear cookies, we can use the injectJavaScript method. For example:

jsx
import React, { useRef } from 'react'; import { WebView } from 'react-native-webview'; const MyWebComponent = () => { const webviewRef = useRef(null); const clearCookies = () => { const script = ` document.cookie.split(";").forEach((c) => { document.cookie = c .replace(/^ +/, "") .replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); true; // note: this is required, or you'll sometimes get silent failures `; webviewRef.current.injectJavaScript(script); }; return ( <WebView ref={webviewRef} source={{ uri: 'https://yourwebsite.com' }} onNavigationStateChange={(event) => { if (event.url === 'https://yourwebsite.com/some-path') { clearCookies(); } }} /> ); }; export default MyWebComponent;

In this example, we define a function clearCookies that creates a JavaScript snippet to clear all cookies. We inject this script into WebView using injectJavaScript.

Method 2: Using the react-native-cookies library

Another approach to handle cookies is by using the react-native-cookies library. First, install this library:

sh
npm install @react-native-cookies/cookies # or yarn add @react-native-cookies/cookies

Then, you can use the clearAll method to clear all cookies:

jsx
import React from 'react'; import { WebView } from 'react-native-webview'; import CookieManager from '@react-native-cookies/cookies'; const MyWebComponent = () => { const clearCookies = async () => { try { await CookieManager.clearAll(); console.log('Cookies cleared!'); } catch (error) { console.error('Failed to clear cookies:', error); } }; // Call clearCookies when needed clearCookies(); return ( <WebView source={{ uri: 'https://yourwebsite.com' }} /> ); }; export default MyWebComponent;

In this example, we use the clearAll method from the @react-native-cookies/cookies library to clear all cookies. This operation is asynchronous, so we use async/await within the clearCookies function.

Both methods can achieve clearing cookies in WebView. The choice depends on the specific application scenario and personal preference.

2024年6月29日 12:07 回复

你的答案