How I resolve Clarity COEP blockage with CORS error

April 18, 2023

Because I have to use asynchronous web apis from WebAssembly, see in article. I choose the SharedArrayBuffer solution. To enable the feature, specific http headers must set to the response of document(html file where wasm run in).

Cross-Origin-Embedder-Policy: credentialless
Cross-Origin-Opener-Policy: same-origin

See the Cross-Origin- prefix , it will cause CORS issues! Learn more about the issues from:

  1. Avoiding COEP blockage with CORS
  2. Setting crossOrigin attribute
  3. Third-party scripts without cors headers

The product depends on Clarity to get analytics, it will suffer CORS issue.

How clarity works? it will dynamically inject a script element, to load some javascript code locate in https://www.clarity.ms, something like code below.

(function (c, l, a, r, i, t, y) {
    c[a] =
      c[a] ||
      function () {
        (c[a].q = c[a].q || []).push(arguments);
      };
    t = l.createElement(r);
    t.async = 1;
    t.src = 'https://www.clarity.ms/tag/' + i;
    
    // it didn't work even if I uncomment the line
    // t.crossOrigin = 'anonymous'
  
    y = l.getElementsByTagName(r)[0];
    y.parentNode.insertBefore(t, y);
  })(window, document, 'clarity', 'script', 'the-real-tag-id');

It shows such error in browser console, NotSameOriginAfterDefaultedToSameOriginByCoep

I tried to set crossOrigin attribute of the script, it still didn't work and showed same error for load a different script.

After inspecting the loaded JavaScript code, I discovered that it injects another script element into the document which causes the error. Additionally, it dynamically requests an image at https://c.clarity.ms/c.gif. I believe both of these actions will encounter the same issue.

Seeing the code, I came through an idea that might work. I can manually send an HTTP request to retrieve the first script content and set the crossOrigin attribute for both image and script elements using a regex pattern. Finally, manually insert a new script element with the replaced content using Javascript.

I can see the analytic data now, which means it's working! However, the browser is still blocking the https://c.clarity.ms/c.gif request due to the response headers doesn't contain correct Access-Control-Allow-Origin header.

I try to figure out what the lacking of c.gif may impact using curl, the request will be redirected multiple times, each response seems just set some cookies, I get nothing more than this.

Additionally, Clarity offers visual analytics such as heatmaps and live user recordings. These tools are particularly helpful in understanding how users interact with the product.

You can view more CORS related issues: https://github.com/microsoft/clarity/issues?q=CORS


Profile picture

Written by Priestch who lives and works in Xi'an building useful things. You can follow him on Github