You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

咨询:跨域Widget无需Cookie维持状态的可行方案及实现原理

How to Maintain Widget State Without Third-Party Cookies (And How Tools Like Intercom Do It)

Great question—third-party cookie restrictions have been a growing headache for embedded widgets, and it’s smart to get ahead of the curve before they’re blocked entirely. Let’s break down practical solutions for your widget, plus dive into how tools like Intercom keep their state stable.

Solutions to Maintain Widget State Without Third-Party Cookies

1. URL Parameter State Passing

If your widget needs to redirect to a new page, encode critical state data into the URL query parameters. This works because URL parameters are accessible across navigations, even without cookies.

Example workflow:

  • When the widget needs to redirect, serialize and encode the state:
    const widgetState = { userId: "123", sessionToken: "abcxyz", preferences: { darkMode: true } };
    const encodedState = btoa(JSON.stringify(widgetState)); // Base64 encode for readability
    window.open(`https://example.com/widget?state=${encodedState}`, "_blank");
    
  • On the target page, decode and restore the state:
    const searchParams = new URLSearchParams(window.location.search);
    const encodedState = searchParams.get("state");
    if (encodedState) {
      const widgetState = JSON.parse(atob(encodedState));
      // Restore widget UI/behavior using this state
    }
    

Note: Avoid putting sensitive data in URLs (they’re stored in browser history). Encrypt sensitive fields if you must include them.

2. Parent-iframe Communication via postMessage

Leverage the browser’s postMessage API to let your main site (mywebsite.com) handle state storage on behalf of the iframe. Since the main site uses first-party storage (cookies, localStorage, sessionStorage), it won’t be blocked by third-party cookie restrictions.

Main site code (mywebsite.com):

// Listen for state requests from the iframe
window.addEventListener("message", (event) => {
  // Validate the origin to prevent XSS attacks
  if (event.origin !== "https://example.com") return;

  if (event.data.type === "REQUEST_WIDGET_STATE") {
    // Pull state from first-party localStorage
    const storedState = localStorage.getItem("widget_session");
    // Send state back to the iframe
    event.source.postMessage(
      { type: "WIDGET_STATE_RESPONSE", data: storedState },
      event.origin
    );
  }
});

// Save state to main site's localStorage when the widget updates
function saveWidgetState(state) {
  localStorage.setItem("widget_session", JSON.stringify(state));
}

Iframe code (example.com):

// Request state from the parent site
window.parent.postMessage(
  { type: "REQUEST_WIDGET_STATE" },
  "https://mywebsite.com"
);

// Listen for the state response
window.addEventListener("message", (event) => {
  if (event.origin !== "https://mywebsite.com") return;

  if (event.data.type === "WIDGET_STATE_RESPONSE") {
    const widgetState = JSON.parse(event.data.data);
    // Restore widget state
  }
});

3. Token-Based Server-Side State Storage

Instead of storing state client-side, keep it on your backend and reference it with a unique token. The main site stores this token in first-party storage, and the iframe uses the token to fetch state from your server.

How it works:

  1. When the widget initializes, your backend generates a unique sessionToken and returns it to the main site.
  2. The main site stores sessionToken in its first-party localStorage or cookie.
  3. The iframe requests the token from the main site via postMessage.
  4. The iframe sends the token to your backend API to retrieve the associated state:
    fetch(`https://example.com/api/widget-state?token=${sessionToken}`)
      .then(res => res.json())
      .then(state => {
        // Restore widget state
      });
    

4. Shared Storage API (Modern Browser Solution)

For browsers that support it, the Shared Storage API lets trusted domains share small amounts of data (up to 10MB) without relying on third-party cookies. You’ll need to configure your domains to be in the same storage partition (via Storage Access Policy headers or domain association files).

Example usage:

// Main site: Save state to shared storage
async function saveSharedState(state) {
  const storage = await navigator.sharedStorage.open();
  await storage.set("widget_state", JSON.stringify(state));
}

// Iframe: Retrieve state from shared storage
async function getSharedState() {
  const storage = await navigator.sharedStorage.open();
  const state = await storage.get("widget_state");
  return JSON.parse(state);
}

Note: This API is still rolling out (supported in Chrome 119+), so you’ll need a fallback for older browsers.

How Intercom & Chat Widgets Maintain Stable State

Tools like Intercom have solved this problem by leaning into first-party integration and server-side state:

  • First-Party Script Execution: Intercom’s widget loads as a script directly on the main site, not an iframe (or uses an iframe controlled by the main site’s script). This lets it use the main site’s first-party storage (cookies, localStorage) to store user session data—no third-party cookies needed.
  • User Identity Mapping: When the main site initializes Intercom, it passes a unique user ID (e.g., window.intercomSettings = { user_id: "customer_123" }). Intercom’s backend links this ID to the user’s chat history and preferences, so even if local storage is cleared, the state can be restored via the user ID.
  • Token-Based Sessions: Intercom generates a persistent token for each user, stored in the main site’s first-party cookie. This token is used to authenticate requests to Intercom’s backend, pulling the latest chat state without relying on third-party storage.
  • Seamless Context Sync: The widget communicates directly with the main site’s script to sync state (like user login status) in real time, ensuring the widget always reflects the user’s current context on the main site.

Key Considerations

  • Security: Always validate postMessage origins, encrypt sensitive data in transit, and avoid storing secrets in client-side storage.
  • Privacy: Comply with regulations like GDPR by asking for user consent before storing data, and provide ways to delete stored state.
  • Compatibility: Test fallback solutions for browsers that don’t support modern APIs like Shared Storage.

内容的提问来源于stack exchange,提问作者Abs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 20:42:48