请求协助:如何让Google Analytics退出代码在Wix网站生效
Hey there, let's work through why your opt-out link isn't working on Wix and fix it step by step.
The core issue here is that Wix blocks inline JavaScript in HTML content (like the javascript:gaOptout() href you tried) for security purposes, plus the gaOptout function might not be accessible in the right scope. Here's how to get it up and running:
Step 1: Make the gaOptout function globally available
First, you need to define the opt-out function in a spot where your entire site can access it.
- Head to your Wix dashboard > Settings > Custom Code
- Click Add Custom Code
- Paste this code (replace
UA-XXXXXXXXX-Ywith your actual Google Analytics tracking ID):
function gaOptout() { // Set a cookie to disable GA tracking site-wide document.cookie = 'ga-disable-UA-XXXXXXXXX-Y=true; expires=Thu, 31 Dec 2099 23:59:59 UTC; path=/'; window['ga-disable-UA-XXXXXXXXX-Y'] = true; // Optional: Notify the user the opt-out was successful alert('You have successfully opted out of Google Analytics tracking.'); }
- Choose to load this code in the Head section, and apply it to All pages (or just the pages where you’ll place the opt-out link)
- Save and publish this change
Step 2: Attach the opt-out function to your text element
Instead of relying on an inline JavaScript link, we’ll add a click event listener directly to your text element via Wix’s page code editor:
- Open the Wix Editor for your target page
- Select the text element (
#text1) you want to use as the opt-out link - Click the Code (</>) icon to open the page code editor
- Replace the existing code with this:
$w.onReady(function () { // Style the text to look like a clickable link $w("#text1").html = "<span style='color: #0066cc; text-decoration: underline; cursor: pointer;'>Click here to opt-out of Google Analytics</span>"; // Trigger the opt-out function when the text is clicked $w("#text1").onClick(() => { gaOptout(); }); });
Step 3: Test the functionality
Publish your site, then click the opt-out text. You’ll see the confirmation alert (if you kept it), and you can verify the cookie was set using your browser’s developer tools (navigate to Application > Cookies > Your site domain — look for the ga-disable-UA-XXXXXXXXX-Y cookie with a value of true).
Quick note for GA4 users
If you’re using Google Analytics 4 instead of the classic ga.js, adjust the gaOptout function to match GA4’s consent model:
function gaOptout() { gtag('consent', 'update', { 'analytics_storage': 'denied' }); alert('You have successfully opted out of Google Analytics 4 tracking.'); }
Just ensure you have the GA4 gtag code loaded on your site first.
内容的提问来源于stack exchange,提问作者Artur

