React.js中修改Referrer-Policy:将Chrome默认策略改为no-referrer-when-downgrade
no-referrer-when-downgrade in a React Project Hey there! Let's break down how to adjust the Referrer-Policy for your React app so it uses no-referrer-when-downgrade instead of Chrome's default strict-origin-when-cross-origin. Here are the most common approaches based on your setup:
1. Add a Meta Tag in Your Entry HTML File
This is the simplest and most universal method for client-side React apps. All you need to do is edit the main HTML file (usually located in the public folder for Create React App, or index.html in the root for Vite) and add a <meta> tag inside the <head> section:
<head> <!-- Other existing meta tags, title, links --> <meta name="referrer" content="no-referrer-when-downgrade"> </head>
This meta tag tells the browser to send the full referrer URL when navigating to HTTPS sites, and omit it only when downgrading to HTTP from HTTPS. It will override Chrome's default policy for all users visiting your app.
2. Configure via Build Tool (If Using Vite or Create React App)
For Vite Projects
If you're using Vite, you can also set the referrer policy directly in your vite.config.js file using header configurations for both dev and production builds:
import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; export default defineConfig({ plugins: [react()], // Set header for development server server: { headers: { 'Referrer-Policy': 'no-referrer-when-downgrade' } }, // Set header for production build build: { rollupOptions: { output: { banner: () => `Referrer-Policy: no-referrer-when-downgrade` } } } });
For Create React App
Create React App doesn't expose direct header configuration in package.json, so the meta tag method above is the recommended approach. If you need to set it via HTTP headers (for server-side control), you'll need to configure your hosting platform (like Netlify, Vercel, or your own backend server) to send the Referrer-Policy header with the desired value.
3. Local Chrome Browser Setting (For Personal Testing)
If you just need to test this policy locally on your own Chrome browser (not for all app users), you can modify Chrome's flags:
- Open Chrome and navigate to
chrome://flags/#referrer-policy - From the dropdown menu, select
No Referrer When Downgrade - Click "Relaunch" to apply the change
Note that this only affects your local browser, not other users visiting your app.
内容的提问来源于stack exchange,提问作者Kamalesh A

